Kotlin HttpURLConnection與服務(wù)器交互實(shí)現(xiàn)方法詳解
1.查詢(get)-調(diào)用的時(shí)候記得開線程
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ù)進(jìn)行處理請(qǐng)求(提交表單、上傳文件),又可能導(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è)置請(qǐng)求頭:
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”的所寫,整個(gè)萬維網(wǎng)都在使用這種協(xié)議,幾乎你在瀏覽器里看到的大部分內(nèi)容都是通過http協(xié)議來傳輸?shù)?
HTTP Headers是HTTP請(qǐng)求和相應(yīng)的核心,它承載了關(guān)于客戶端瀏覽器,請(qǐng)求頁面,服務(wù)器等相關(guān)的信息.
設(shè)置body(請(qǐng)求內(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() }
有時(shí)候開發(fā)的時(shí)候你能看到一個(gè)名叫token的東西,這個(gè)玩意是后臺(tái)自定義的東西,有時(shí)候可以放在請(qǐng)求頭,有時(shí)候可以放在body里面,具體可以看協(xié)議
3.增(PUT)
PUT:這個(gè)方法比較少見。HTML表單也不支持這個(gè)。本質(zhì)上來講, PUT和POST極為相似,都是向服務(wù)器發(fā)送數(shù)據(jù),但它們之間有一個(gè)重要區(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請(qǐng)求)
DELETE:刪除某一個(gè)資源。基本上這個(gè)也很少見,我只在像亞馬遜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ù)器交互實(shí)現(xiàn)方法詳解的文章就介紹到這了,更多相關(guān)Kotlin HttpURLConnection與服務(wù)器交互內(nèi)容請(qǐng)搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
- Android開發(fā)使用json實(shí)現(xiàn)服務(wù)器與客戶端數(shù)據(jù)的交互功能示例
- Android實(shí)現(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進(jìn)行網(wǎng)絡(luò)編程詳解【附源碼下載】
- Android基于HttpUrlConnection類的文件下載實(shí)例代碼
- Android網(wǎng)絡(luò)技術(shù)HttpURLConnection詳解
相關(guān)文章
Android用RecyclerView實(shí)現(xiàn)圖標(biāo)拖拽排序以及增刪管理
這篇文章主要介紹了Android用RecyclerView實(shí)現(xiàn)圖標(biāo)拖拽排序以及增刪管理的方法,幫助大家更好的理解和學(xué)習(xí)使用Android,感興趣的朋友可以了解下2021-03-03android手機(jī)獲取唯一標(biāo)識(shí)的方法
這篇文章主要 為大家詳細(xì)介紹了android手機(jī)獲取唯一標(biāo)識(shí)的方法,具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下2017-06-06Android仿360桌面手機(jī)衛(wèi)士懸浮窗效果
這篇文章主要介紹了Android仿360手機(jī)衛(wèi)士懸浮窗效果的桌面實(shí)現(xiàn),小編覺得挺不錯(cuò)的,現(xiàn)在分享給大家,也給大家做個(gè)參考。一起跟隨小編過來看看吧2018-05-05Android標(biāo)題欄最右邊添加按鈕的實(shí)例
這篇文章主要介紹了Android標(biāo)題欄最右邊添加按鈕的實(shí)例的相關(guān)資料,希望通過本文大家能掌握如何操作,需要的朋友可以參考下2017-09-09Android Webview上的ssl warning的處理方式詳解及實(shí)例
這篇文章主要介紹了Android Webview上的ssl warning的處理方式詳解及實(shí)例的相關(guān)資料,需要的朋友可以參考下2017-02-02Android中使用TextView實(shí)現(xiàn)圖文混排的方法
向TextView或EditText中添加圖像比直接添加文本復(fù)雜一點(diǎn)點(diǎn),需要用到<img>標(biāo)簽。接下來通過本文給大家介紹Android中使用TextView實(shí)現(xiàn)圖文混排的方法,希望對(duì)大家有所幫助2016-02-02Android使用ViewFlipper實(shí)現(xiàn)圖片上下自動(dòng)輪播的示例代碼
這篇文章主要介紹了Android使用ViewFlipper實(shí)現(xiàn)圖片上下自動(dòng)輪播的示例代碼,文中通過示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧2021-05-05Android Studio的安裝及第一次啟動(dòng)時(shí)的配置問題
這篇文章主要介紹了Android Studio的安裝及第一次啟動(dòng)時(shí)的配置,需要的朋友可以參考下2019-09-09