KotlinHttpURLConnection與服務(wù)器交互實(shí)現(xiàn)方法詳解_第1頁
KotlinHttpURLConnection與服務(wù)器交互實(shí)現(xiàn)方法詳解_第2頁
KotlinHttpURLConnection與服務(wù)器交互實(shí)現(xiàn)方法詳解_第3頁
KotlinHttpURLConnection與服務(wù)器交互實(shí)現(xiàn)方法詳解_第4頁
KotlinHttpURLConnection與服務(wù)器交互實(shí)現(xiàn)方法詳解_第5頁
已閱讀5頁,還剩2頁未讀 繼續(xù)免費(fèi)閱讀

下載本文檔

版權(quán)說明:本文檔由用戶提供并上傳,收益歸屬內(nèi)容提供方,若內(nèi)容存在侵權(quán),請(qǐng)進(jìn)行舉報(bào)或認(rèn)領(lǐng)

文檔簡介

第KotlinHttpURLConnection與服務(wù)器交互實(shí)現(xiàn)方法詳解目錄1.查詢(get)-調(diào)用的時(shí)候記得開線程2.改(post)3.增(PUT)4.刪(DELETE請(qǐng)求)

1.查詢(get)-調(diào)用的時(shí)候記得開線程

GET一般用于獲取/查詢資源信息

valsb=StringBuffer()

try{

valurl=URL(url)

valconn=url.openConnection()asHttpURLConnection

conn.requestMethod="GET"

conn.connectTimeout=5000

valcode=conn.responseCode

if(code==200){

val`is`=conn.inputStream

valb=ByteArray(1024)

varlen: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)致新的資源的建立或原有資源的修改。

valsb=StringBuffer()

object:Thread(){

overridefunrun(){

super.run()

try{

valurl=URL(urlPath)

valconn=url.openConnection()asHttpURLConnection

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)){

valwritebytes=Json.toByteArray()

conn.setRequestProperty("Content-Length",writebytes.size.toString())

valoutwritestream=conn.outputStream

outwritestream.write(Json.toByteArray())

outwritestream.flush()

outwritestream.close()

valcode=conn.responseCode

if(code==200){

val`is`=conn.inputStream

valb=ByteArray(1024)

varlen: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,"TXPostsb====$sb")

}else{

Log.w(TAG,"TXPostcode====$code")

}catch(var1:Exception){

Log.w(TAG,"TXPostException====$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是HypertextTransferProtocol的所寫,整個(gè)萬維網(wǎng)都在使用這種協(xié)議,幾乎你在瀏覽器里看到的大部分內(nèi)容都是通過http協(xié)議來傳輸?shù)?

HTTPHeaders是HTTP請(qǐng)求和相應(yīng)的核心,它承載了關(guān)于客戶端瀏覽器,請(qǐng)求頁面,服務(wù)器等相關(guān)的信息.

設(shè)置body(請(qǐng)求內(nèi)容)

if(Json!=null!TextUtils.isEmpty(Json)){

valwritebytes=Json.toByteArray()

conn.setRequestProperty("Content-Length",writebytes.size.toString())

valoutwritestream=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ù)器自己決定。

valurl=URL(urlPath)

valconnection=url.openConnection()asHttpURLConnection

valoutputStream=connection.outputStream

valinputStream=FileInputStream(file)

object:Thread(){

overridefunrun(){

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()

valbytes=ByteArray(

getFileOrFilesSize(file.absolutePath).toInt()

varlength:Int

while(inputStream.read(bytes).also{length=it}!=-1){

outputStream.write(bytes,0,length)

outputStream.flush()

valresponse=connection.inputStream

valreader=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ù)器見過!

valsb=StringBuffer()

varuri:URL=null

varcon:HttpURLConnection=null

try{

uri=URL(url)

con=uri.openConnection()asHttpURLConnection

con.requestMethod="DELETE"

con.doOutput=true

con.doInput=true

con.connectTimeout=60000//60secs

con.readTimeout=60000//60secs

valcode=con.responseCode

if(code==200){

val`is`=con.inputStream

valb=ByteArray(1024)

varlen:Int

while(`is`.

溫馨提示

  • 1. 本站所有資源如無特殊說明,都需要本地電腦安裝OFFICE2007和PDF閱讀器。圖紙軟件為CAD,CAXA,PROE,UG,SolidWorks等.壓縮文件請(qǐng)下載最新的WinRAR軟件解壓。
  • 2. 本站的文檔不包含任何第三方提供的附件圖紙等,如果需要附件,請(qǐng)聯(lián)系上傳者。文件的所有權(quán)益歸上傳用戶所有。
  • 3. 本站RAR壓縮包中若帶圖紙,網(wǎng)頁內(nèi)容里面會(huì)有圖紙預(yù)覽,若沒有圖紙預(yù)覽就沒有圖紙。
  • 4. 未經(jīng)權(quán)益所有人同意不得將文件中的內(nèi)容挪作商業(yè)或盈利用途。
  • 5. 人人文庫網(wǎng)僅提供信息存儲(chǔ)空間,僅對(duì)用戶上傳內(nèi)容的表現(xiàn)方式做保護(hù)處理,對(duì)用戶上傳分享的文檔內(nèi)容本身不做任何修改或編輯,并不能對(duì)任何下載內(nèi)容負(fù)責(zé)。
  • 6. 下載文件中如有侵權(quán)或不適當(dāng)內(nèi)容,請(qǐng)與我們聯(lián)系,我們立即糾正。
  • 7. 本站不保證下載資源的準(zhǔn)確性、安全性和完整性, 同時(shí)也不承擔(dān)用戶因使用這些下載資源對(duì)自己和他人造成任何形式的傷害或損失。

評(píng)論

0/150

提交評(píng)論