Kotlin HttpURLConnection与服务器交互实现方法详解
作者:ui不是我画的
1.查询(get)-调用的时候记得开线程
GET一般用于获取/查询资源信息
val sb = StringBuffer() try { val url = URL(url) val conn = url.openConnection() as HttpURLConnection conn.requestMethod = "GET" conn.connectTimeout = 5000 val code = conn.responseCode if (code == 200) { val `is` = conn.inputStream val b = ByteArray(1024) var len: Int while (`is`.read(b).also { len = it } != -1) { sb.append(String(b, 0, len, Charset.forName("UTF-8"))) } `is`.close() conn.disconnect() Log.e("TAG","sb==${sb.toString()}") } else { Log.e("TAG","code==${code.toString()}") } } catch (var1: Exception) { Log.e("TAG","Exception==${var1.message}") }
2.改(post)
post向指定资源提交数据进行处理请求(提交表单、上传文件),又可能导致新的资源的建立或原有资源的修改。
val sb = StringBuffer() object : Thread() { override fun run() { super.run() try { val url = URL(urlPath) val conn = url.openConnection() as HttpURLConnection conn.doOutput = true conn.requestMethod = "POST" conn.connectTimeout = 5000 conn.doInput = true conn.useCaches = false conn.setRequestProperty("Connection", "Keep-Alive") conn.setRequestProperty("Charset", "UTF-8") conn.setRequestProperty("Content-Type", "application/json; charset=UTF-8") conn.setRequestProperty("accept", "application/json") conn.setRequestProperty("appid", mAPP_ID) conn.setRequestProperty("ts", time) conn.setRequestProperty("sign", sign) Log.e(TAG, "Json:$Json") if (Json != null && !TextUtils.isEmpty(Json)) { val writebytes = Json.toByteArray() conn.setRequestProperty("Content-Length", writebytes.size.toString()) val outwritestream = conn.outputStream outwritestream.write(Json.toByteArray()) outwritestream.flush() outwritestream.close() } val code = conn.responseCode if (code == 200) { val `is` = conn.inputStream val b = ByteArray(1024) var len: Int while (`is`.read(b).also { len = it } != -1) { sb.append(String(b, 0, len, Charset.forName("UTF-8"))) } `is`.close() conn.disconnect() Log.w(TAG, "TXPost sb====$sb") } else { Log.w(TAG, "TXPost code====$code") } } catch (var1: Exception) { Log.w(TAG, "TXPost Exception====$var1") } } }.start()
设置请求头:
1.基本headers 这四句一般没有特殊需求的话,都是需要的
conn.setRequestProperty("Connection", "Keep-Alive")
conn.setRequestProperty("Charset", "UTF-8")
conn.setRequestProperty("Content-Type", "application/json; charset=UTF-8")
conn.setRequestProperty("accept", "application/json")
2.特殊headers 这些是客户端与服务通信服务器所需的headers
conn.setRequestProperty("appid", mAPP_ID)
conn.setRequestProperty("ts", time)
conn.setRequestProperty("sign", sign)
Headers:
HTTP是“Hypertext Transfer Protocol”的所写,整个万维网都在使用这种协议,几乎你在浏览器里看到的大部分内容都是通过http协议来传输的.
HTTP Headers是HTTP请求和相应的核心,它承载了关于客户端浏览器,请求页面,服务器等相关的信息.
设置body(请求内容)
if (Json != null && !TextUtils.isEmpty(Json)) { val writebytes = Json.toByteArray() conn.setRequestProperty("Content-Length", writebytes.size.toString()) val outwritestream = conn.outputStream outwritestream.write(Json.toByteArray()) outwritestream.flush() outwritestream.close() }
有时候开发的时候你能看到一个名叫token的东西,这个玩意是后台自定义的东西,有时候可以放在请求头,有时候可以放在body里面,具体可以看协议
3.增(PUT)
PUT:这个方法比较少见。HTML表单也不支持这个。本质上来讲, PUT和POST极为相似,都是向服务器发送数据,但它们之间有一个重要区别,PUT通常指定了资源的存放位置,而POST则没有,POST的数据存放位置由服务器自己决定。
val url = URL(urlPath) val connection = url.openConnection() as HttpURLConnection val outputStream = connection.outputStream val inputStream = FileInputStream(file) object : Thread() { override fun run() { super.run() try { connection.doOutput = true connection.useCaches = false connection.setRequestProperty("Accept-Charset", "utf-8") connection.setRequestProperty("Connection", "keep-alive") connection.setRequestProperty( "Content-Type", "multipart/form-data;boundary=fengexian====" ) connection.setRequestProperty("Accept", "application/json") connection.connect() val bytes = ByteArray( getFileOrFilesSize(file.absolutePath).toInt() ) var length: Int while (inputStream.read(bytes).also { length = it } != -1) { outputStream.write(bytes, 0, length) } outputStream.flush() val response = connection.inputStream val reader = InputStreamReader(response) while (reader.read() != -1) { String(bytes, Charset.forName("UTF-8")) } if (connection.responseCode == 200) { Log.w("TAG", "connection===${connection.responseMessage}") } else { Log.w("TAG", "responseCode===${connection.responseCode}") } } catch (var13: IOException) { Log.w("TAG", "IOException===${var13.message}") } finally { try { outputStream.close() inputStream.close() connection.disconnect() } catch (var12: IOException) { var12.printStackTrace() } } } }.start()
4.删(DELETE请求)
DELETE:删除某一个资源。基本上这个也很少见,我只在像亚马逊s3之类的服务器见过!
val sb = StringBuffer() var uri: URL? = null var con: HttpURLConnection? = null try { uri = URL(url) con = uri.openConnection() as HttpURLConnection con.requestMethod = "DELETE" con.doOutput = true con.doInput = true con.connectTimeout = 60000 //60 secs con.readTimeout = 60000 //60 secs val code = con.responseCode if (code == 200) { val `is` = con.inputStream val b = ByteArray(1024) var len: Int while (`is`.read(b).also { len = it } != -1) { sb.append(String(b, 0, len, Charset.forName("UTF-8"))) } `is`.close() con.disconnect() Log.w("TAG", "sb===${sb}") } else { Log.w("TAG", "code===$[code]") } } catch (e: Exception) { Log.w("TAG", "Exception===${e.message}") }
到此这篇关于Kotlin HttpURLConnection与服务器交互实现方法详解的文章就介绍到这了,更多相关Kotlin HttpURLConnection与服务器交互内容请搜索脚本之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持脚本之家!