最新国产好看的视频,伊人天堂AV在线,国产Aaaaaa视频,蜜臀视频在线观看一区,人妻av色图,密臀久久久精品影片,青青视频免费观看毛片,久草在线观看视,国产三级精品色情在线

Kotlin HttpURLConnection與服務(wù)器交互實(shí)現(xiàn)方法詳解

 更新時(shí)間:2022年09月29日 08:29:03   作者:ui不是我畫的  
簡單來說,HttpURLConnection 是發(fā)起HTTP請求的基礎(chǔ)類庫,提供了HTTP請求的基本功能,不過封裝的比較少,在使用時(shí)很多內(nèi)容都需要自己設(shè)置,也需要自己處理請求流和響應(yīng)流

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)行處理請求(提交表單、上傳文件),又可能導(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”的所寫,整個(gè)萬維網(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()
  }

有時(shí)候開發(fā)的時(shí)候你能看到一個(gè)名叫token的東西,這個(gè)玩意是后臺自定義的東西,有時(shí)候可以放在請求頭,有時(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請求)

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)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!

相關(guān)文章

  • Android 自定義Dialog 實(shí)例

    Android 自定義Dialog 實(shí)例

    本篇文章主要介紹Android自定義Dialog,在Android開發(fā)中,出于美觀系統(tǒng)自帶的Dialog一般都會被重新,這里給大家寫個(gè)小實(shí)例,大家可以參考下
    2016-07-07
  • Android自定義View實(shí)現(xiàn)多圖片選擇控件

    Android自定義View實(shí)現(xiàn)多圖片選擇控件

    這篇文章主要為大家詳細(xì)介紹了Android自定義View實(shí)現(xiàn)多圖片選擇控件,具有一定的實(shí)用性,感興趣的小伙伴們可以參考一下
    2016-08-08
  • Kotlin線程的橋接與切換使用介紹

    Kotlin線程的橋接與切換使用介紹

    這篇文章主要介紹了Android開發(fā)中Kotlin線程的橋接與切換,文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧
    2022-08-08
  • Android實(shí)現(xiàn)自制和播放錄音程序

    Android實(shí)現(xiàn)自制和播放錄音程序

    這篇文章主要為大家詳細(xì)介紹了Android實(shí)現(xiàn)自制和播放錄音程序,具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下
    2016-09-09
  • DrawerLayout結(jié)合Tollbar實(shí)現(xiàn)菜單側(cè)滑效果

    DrawerLayout結(jié)合Tollbar實(shí)現(xiàn)菜單側(cè)滑效果

    這篇文章主要為大家詳細(xì)介紹了DrawerLayout結(jié)合Tollbar實(shí)現(xiàn)菜單側(cè)滑效果,具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下
    2017-12-12
  • Kotlin使用滾動控件RecyclerView實(shí)例教程

    Kotlin使用滾動控件RecyclerView實(shí)例教程

    RecyclerView是Android一個(gè)更強(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è)滑刪除功能

    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簡易計(jì)算器的制作

    android簡易計(jì)算器的制作

    這篇文章主要為大家詳細(xì)介紹了android簡易計(jì)算器的制作,文中示例代碼介紹的非常詳細(xì),具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下
    2020-07-07
  • Android Studio Gradle 更換阿里云鏡像的方法

    Android Studio Gradle 更換阿里云鏡像的方法

    這篇文章主要介紹了Android Studio Gradle 更換阿里云鏡像的方法,文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧
    2020-09-09
  • jarsigner重新簽名apk無法安裝的解決方法

    jarsigner重新簽名apk無法安裝的解決方法

    這篇文章主要介紹了jarsigner重新簽名apk無法安裝的解決方法,需要的朋友可以參考下
    2014-04-04

最新評論

藁城市| 玉田县| 昌江| 东台市| 钟祥市| 于都县| 当涂县| 望都县| 康马县| 阿坝县| 兴山县| 武穴市| 晋州市| 大方县| 铁力市| 报价| 汉源县| 上高县| 永靖县| 沈丘县| 芷江| 廉江市| 淮阳县| 赤城县| 长汀县| 阿拉尔市| 浏阳市| 通化市| 保康县| 太保市| 会理县| 彩票| 阆中市| 西盟| 金湖县| 石门县| 昆明市| 涞源县| 清水河县| 东平县| 莎车县|