zoukankan      html  css  js  c++  java
  • Android Kotlin 连接 http

      由于近期网上搜索了很多Android连接到http的方法, 可是2013年以前的方法现在都不能用了,要么报错,要么被遗弃,岁月留下来的东西只能自己整理了。

      其实很简单,就一个HttpUtil通用类。可以实现Get和Post方法,其他东西,里面可以随便改改,基本就这样吧。

      参数的话,我用了一个 strUrlPath网址、params键值对、encode编码(如utf-8)。

      

    package Util
    
    import android.os.Handler
    import android.os.Message
    import android.view.View
    import android.widget.Button
    import java.io.BufferedReader
    import java.io.ByteArrayOutputStream
    import java.io.IOException
    import java.io.InputStream
    import java.io.InputStreamReader
    import java.io.OutputStream
    import java.net.HttpURLConnection
    import java.net.MalformedURLException
    import java.net.URL
    import java.net.URLEncoder
    
    /**
     * Created by Jason_Jan on 2017/7/5.
     */
    
    object HttpUtil {
    
    
        private var handler: Handler? = null
        private var my_result: String? = null
    
        fun httpGet(strUrlPath: String, params: Map<String, String>, encode: String): String {
            var strUrlPath = strUrlPath
            /* byte[] data = getRequestData(params, encode).toString().getBytes();//获得请求体*/
            /* String target="http://emb.mobi/register";*/
            var result: String? = null
            val append_url = getRequestData(params, encode).toString()
            strUrlPath = strUrlPath + "?" + append_url
            try {
                val url = URL(strUrlPath)
                val urlConn = url.openConnection() as HttpURLConnection
                urlConn.connectTimeout = 5000//超时时间
                urlConn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded")//设置头部信息,其实没什么用
    
                //主角开始登场,不注意就是几个小时的调试,输入流
                val `in` = InputStreamReader(urlConn.inputStream)
    
                val buffer = BufferedReader(`in`)
                var inputLine: String? = null
                //循环逐行读取输入流中的内容
    
                result = ""//每次清空数据
    
                while (buffer.readLine().apply { inputLine = this } != null) {
                    result += inputLine!! + "
    "
                }
    
    
                `in`.close()
                urlConn.disconnect()
    
    
            } catch (e: MalformedURLException) {
                e.printStackTrace()
            } catch (ioe: IOException) {
                ioe.printStackTrace()
                return "err:" + ioe.message.toString()
            }
    
            return result!!
    
        }
    
    
        private fun getRequestData(params: Map<String, String>, encode: String): StringBuffer {
            val stringBuffer = StringBuffer()        //存储封装好的请求体信息
            try {
                for ((key, value) in params) {
                    stringBuffer.append(key)
                            .append("=")
                            .append(URLEncoder.encode(value, encode))
                            .append("&")
                }
                stringBuffer.deleteCharAt(stringBuffer.length - 1)    //删除最后的一个"&"
            } catch (e: Exception) {
                e.printStackTrace()
            }
    
            return stringBuffer
        }
    
    
        fun httpPost(strUrlPath: String, params: Map<String, String>, encode: String): String {
            val data = getRequestData(params, encode).toString().toByteArray()
            try {
                val url = URL(strUrlPath)
    
                val http = url.openConnection() as HttpURLConnection
                http.connectTimeout = 5000
                http.doInput = true
                http.doOutput = true
                http.requestMethod = "POST"
                http.useCaches = false//使用post方式不能用缓存
                //设置请求体的类型是文本类型
                http.setRequestProperty("Content-Type", "application/x-www-form-urlencoded")
                //设置请求体的长度
                http.setRequestProperty("Content-Length", data.size.toString())
                //获得输出流,向服务器写入数据
                val out = http.outputStream
                out.write(data)
    
                val response = http.responseCode
                if (response == HttpURLConnection.HTTP_OK) {
                    val inputStream = http.inputStream
                    return dealResponseResult(inputStream)
                }
    
    
            } catch (ioe: IOException) {
                ioe.printStackTrace()
                return "err:" + ioe.message.toString()
            }
    
            return "-1"
        }
    
    
        fun dealResponseResult(inputStream: InputStream): String {
            var resultData: String? = null      //存储处理结果
            val byteArrayOutputStream = ByteArrayOutputStream()
            val data = ByteArray(1024)
            var len = 0
            try {
                while (inputStream.read(data).apply { len = this } != -1) {
                    byteArrayOutputStream.write(data, 0, len)
                }
            } catch (e: IOException) {
                e.printStackTrace()
            }
    
            resultData = String(byteArrayOutputStream.toByteArray())
            return resultData
        }
    }
    
       
    

      

      

      使用方式很简单--HttpUtil.方法名(参数),返回一个string,之后用Json解析工具来解析。

      其次重中之重,安卓网络连接有点坑。下面从两个方面谈谈。

      1.getoutputstream这里,一直报错。解决方案:build.gradle

    compile 'com.squareup.retrofit:retrofit:1.8.0'
    compile 'com.squareup.okhttp:okhttp:2.1.0'
    compile 'com.squareup.okhttp:okhttp-urlconnection:2.1.0'

      2.其次,在AndroidManifest.xml中

    <uses-permission android:name="android.permission.ACCESS_WIFI_STATE" />
    <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
    <uses-permission android:name="android.permission.INTERNET" />  
    

      

      

      

    既然选择了,便不顾风雨兼程。Just follow yourself.
  • 相关阅读:
    安装IDM扩展
    Go_数组&切片
    Mycat概念&安装
    IDEA自定义主题
    完全卸载Oracle11g
    创建型模式——单例模式(Singleton)
    设计模式统计
    PHP解压带密码的zip文件
    Win推荐软件
    如何设置线程池的线程数?
  • 原文地址:https://www.cnblogs.com/Jason-Jan/p/7127082.html
Copyright © 2011-2022 走看看