Kotlin HttpURLConnection與服務(wù)器交互實(shí)現(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ù)進(jìn)行處理請求(提交表單、上傳文件),又可能導(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ù)器交互實(shí)現(xiàn)方法詳解的文章就介紹到這了,更多相關(guān)Kotlin HttpURLConnection與服務(wù)器交互內(nèi)容請搜索腳本之家以前的文章或繼續(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自定義View實(shí)現(xiàn)多圖片選擇控件
這篇文章主要為大家詳細(xì)介紹了Android自定義View實(shí)現(xiàn)多圖片選擇控件,具有一定的實(shí)用性,感興趣的小伙伴們可以參考一下2016-08-08
DrawerLayout結(jié)合Tollbar實(shí)現(xiàn)菜單側(cè)滑效果
這篇文章主要為大家詳細(xì)介紹了DrawerLayout結(jié)合Tollbar實(shí)現(xiàn)菜單側(cè)滑效果,具有一定的參考價值,感興趣的小伙伴們可以參考一下2017-12-12
Kotlin使用滾動控件RecyclerView實(shí)例教程
RecyclerView是Android一個更強(qiáng)大的控件,其不僅可以實(shí)現(xiàn)和ListView同樣的效果,還有優(yōu)化了ListView中的各種不足。其可以實(shí)現(xiàn)數(shù)據(jù)縱向滾動,也可以實(shí)現(xiàn)橫向滾動(ListView做不到橫向滾動)。接下來講解RecyclerView的用法2022-12-12
Android使用Item Swipemenulistview實(shí)現(xiàn)仿QQ側(cè)滑刪除功能
大家都用過QQ,肯定有人好奇QQ滑動刪除Item的效果是怎樣實(shí)現(xiàn)的,其實(shí)我們使用Swipemenulistview就可以簡單的實(shí)現(xiàn)。這篇文章主要介紹了Android使用ItemSwipemenulistview實(shí)現(xiàn)仿QQ側(cè)滑刪除功能,需要的朋友可以參考下2017-02-02
Android Studio Gradle 更換阿里云鏡像的方法
這篇文章主要介紹了Android Studio Gradle 更換阿里云鏡像的方法,文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧2020-09-09

