美文网首页Net
kotlin okhttp post请求 例子

kotlin okhttp post请求 例子

作者: StormerX | 来源:发表于2019-10-10 17:01 被阅读0次

    简单举例okhttp发送post请求。
    比如说发送post请求,API的地址是https://www.abc.com/api/test,参数是username。

    首先引用包名

    import okhttp3.*
    import okhttp3.RequestBody.Companion.toRequestBody
    

    构建post参数和请求

    val urlAPI: String = "https://www.abc.com/api/test"
    
    val builder = FormBody.Builder()
    builder.add("username",  "彭裤子")
    val formBody = builder.build()
    
    val request = Request.Builder()
                    .method("POST", formBody)
                    .url(urlAPI).build()
    
    
    val client = OkHttpClient()
    
    client.newCall(request).enqueue(object : Callback {
    
    override fun onResponse(call: Call, response: Response) {
        val result = response.body?.string()
        println("result:" + result)
    }
    
    override fun onFailure(call: Call, e: IOException) {
        println("Failed request api :( " + e.message)
    }
    
    })
    

    相关文章

      网友评论

        本文标题:kotlin okhttp post请求 例子

        本文链接:https://www.haomeiwen.com/subject/vsfapctx.html