Kotlin HttpURLConnection與服務(wù)器交互實現(xiàn)方法詳解
1.查詢(get)-調(diào)用的時候記得開線程
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向指定資源提交數(shù)據(jù)進行處理請求(提交表單、上傳文件),又可能導(dǎo)致新的資源的建立或原有資源的修改。
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()
設(shè)置請求頭:
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 這些是客戶端與服務(wù)通信服務(wù)器所需的headers
conn.setRequestProperty("appid", mAPP_ID)
conn.setRequestProperty("ts", time)
conn.setRequestProperty("sign", sign)
Headers:
HTTP是“Hypertext Transfer Protocol”的所寫,整個萬維網(wǎng)都在使用這種協(xié)議,幾乎你在瀏覽器里看到的大部分內(nèi)容都是通過http協(xié)議來傳輸?shù)?
HTTP Headers是HTTP請求和相應(yīng)的核心,它承載了關(guān)于客戶端瀏覽器,請求頁面,服務(wù)器等相關(guān)的信息.
設(shè)置body(請求內(nèi)容)
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() }
有時候開發(fā)的時候你能看到一個名叫token的東西,這個玩意是后臺自定義的東西,有時候可以放在請求頭,有時候可以放在body里面,具體可以看協(xié)議
3.增(PUT)
PUT:這個方法比較少見。HTML表單也不支持這個。本質(zhì)上來講, PUT和POST極為相似,都是向服務(wù)器發(fā)送數(shù)據(jù),但它們之間有一個重要區(qū)別,PUT通常指定了資源的存放位置,而POST則沒有,POST的數(shù)據(jù)存放位置由服務(wù)器自己決定。
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之類的服務(wù)器見過!
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}") }
到此這篇關(guān)于Kotlin HttpURLConnection與服務(wù)器交互實現(xiàn)方法詳解的文章就介紹到這了,更多相關(guān)Kotlin HttpURLConnection與服務(wù)器交互內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
- Android開發(fā)使用json實現(xiàn)服務(wù)器與客戶端數(shù)據(jù)的交互功能示例
- Android實現(xiàn)與Apache Tomcat服務(wù)器數(shù)據(jù)交互(MySql數(shù)據(jù)庫)
- 詳解Android客戶端與服務(wù)器交互方式
- Android HttpURLConnection下載網(wǎng)絡(luò)圖片設(shè)置系統(tǒng)壁紙
- Android 用HttpURLConnection訪問網(wǎng)絡(luò)的方法
- Android開發(fā)使用HttpURLConnection進行網(wǎng)絡(luò)編程詳解【附源碼下載】
- Android基于HttpUrlConnection類的文件下載實例代碼
- Android網(wǎng)絡(luò)技術(shù)HttpURLConnection詳解
相關(guān)文章
Android用RecyclerView實現(xiàn)圖標拖拽排序以及增刪管理
這篇文章主要介紹了Android用RecyclerView實現(xiàn)圖標拖拽排序以及增刪管理的方法,幫助大家更好的理解和學習使用Android,感興趣的朋友可以了解下2021-03-03Android Webview上的ssl warning的處理方式詳解及實例
這篇文章主要介紹了Android Webview上的ssl warning的處理方式詳解及實例的相關(guān)資料,需要的朋友可以參考下2017-02-02Android中使用TextView實現(xiàn)圖文混排的方法
向TextView或EditText中添加圖像比直接添加文本復(fù)雜一點點,需要用到<img>標簽。接下來通過本文給大家介紹Android中使用TextView實現(xiàn)圖文混排的方法,希望對大家有所幫助2016-02-02Android使用ViewFlipper實現(xiàn)圖片上下自動輪播的示例代碼
這篇文章主要介紹了Android使用ViewFlipper實現(xiàn)圖片上下自動輪播的示例代碼,文中通過示例代碼介紹的非常詳細,對大家的學習或者工作具有一定的參考學習價值,需要的朋友們下面隨著小編來一起學習學習吧2021-05-05