今日长缨在手,何时缚住苍龙。这篇文章主要讲述Android Kotlin 连接 http相关的知识,希望能为你提供帮助。
由于近期网上搜索了很多android连接到http的方法, 可是2013年以前的方法现在都不能用了,要么报错,要么被遗弃,岁月留下来的东西只能自己整理了。
其实很简单,就一个HttpUtil通用类。可以实现Get和Post方法,其他东西,里面可以随便改改,基本就这样吧。
参数的话,我用了一个 strUrlPath网址、params键值对、encode编码(如utf-8)。
package Utilimport 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? = nullfun httpGet(strUrlPath: String, params: Map< String, String> , encode: String): String { var strUrlPath = strUrlPath /* byte[] data = https://www.songbingjia.com/android/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!! + "\n" }`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 = https://www.songbingjia.com/android/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 = https://www.songbingjia.com/android/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" />
【Android Kotlin 连接 http】
推荐阅读
- 亲测appium_v1.4.16版本自动化适配android7.0系统
- 企业为什么需要定制自己的App()
- 不想手动输入车牌号(手机Android端车牌识别助你一臂之力!)
- Appium 如何模拟返回按键
- Android 打开设置界面或者WiFi连接界面
- 前端如何将H5页面打包成本地app()
- 对Appium的认识 get
- Android 按压状态改变背景色
- Android实例-ImageList与Image的应用