如何使用Kotlin进行HTTP POST方法请求

5

我是一名新的Kotlin开发者,请教如何在Kotlin中使用httpRequest。

问题 - 如果我想要请求API服务并且必须通过POST方法发送带有json对象的请求正文,我该怎么写?

谢谢你的帮助。

3个回答

7
您可以使用outputStream.write(postData)来编写您的数据。
 fun pushToChat(message: String) {

        val serverURL: String = "your URL"
        val url = URL(serverURL)
        val connection = url.openConnection() as HttpURLConnection
        connection.requestMethod = "POST"
        connection.connectTimeout = 300000
        connection.doOutput = true

        val postData: ByteArray = message.toByteArray(StandardCharsets.UTF_8)

        connection.setRequestProperty("charset", "utf-8")
        connection.setRequestProperty("Content-length", postData.size.toString())
        connection.setRequestProperty("Content-Type", "application/json")

        try {
            val outputStream: DataOutputStream = DataOutputStream(connection.outputStream)
            outputStream.write(postData)
            outputStream.flush()
        } catch (exception: Exception) {

        }

        if (connection.responseCode != HttpURLConnection.HTTP_OK && connection.responseCode != HttpURLConnection.HTTP_CREATED) {
            try {
                val inputStream: DataInputStream = DataInputStream(connection.inputStream)
                val reader: BufferedReader = BufferedReader(InputStreamReader(inputStream))
                val output: String = reader.readLine()

                println("There was error while connecting the chat $output")
                System.exit(0)

            } catch (exception: Exception) {
                throw Exception("Exception while push the notification  $exception.message")
            }
        }

    }

在 Kotlin 中,我需要导入哪些软件包? - Vivek Kumar
1
还出现了错误:函数调用 'inputStream(...)' 预期 - Vivek Kumar
小心打错字:“Content-length”。 - poqueque
基于 Content-lenght 的拼写错误,可以推测这段代码从未被执行过。 - Wyck
执行代码后,我们还可以推断出只有一个小错误。 - Phani Rithvij

1
您还使用了Retrofit 2.0,像下面这样在gradle文件中添加依赖...
  compile 'com.squareup.retrofit2:retrofit:2.3.0'

将每个 API 调用和数据显示在 log cat 中,添加以下依赖项...

    compile 'com.squareup.okhttp3:logging-interceptor:3.4.1'

然后创建一个API设置的类,如下所示...

class ApiClient {

companion object {
    val BASE_URL = "https://simplifiedcoding.net/demos/"
    var retrofit: Retrofit? = null
    fun getClient(): Retrofit? {
        if (retrofit == null) {
            val interceptor = HttpLoggingInterceptor()
            interceptor.level = HttpLoggingInterceptor.Level.BODY
            val client = OkHttpClient.Builder().apply {
            readTimeout(20, TimeUnit.SECONDS)
            writeTimeout(20, TimeUnit.SECONDS)
            connectTimeout(20, TimeUnit.SECONDS)
            addInterceptor(interceptor)
            addInterceptor { chain ->
                var request = chain.request()
                request = request.newBuilder()
                        .build()
                val response = chain.proceed(request)
                response
            }
            }
            retrofit = Retrofit.Builder()
                    .baseUrl(BASE_URL)
                    .client(client.build())

                    .addConverterFactory(GsonConverterFactory.create())
                    .build()

        }

        return retrofit
    }
}

}

然后制作接口来调用不同类型的API,如下所示...
interface ApiInterface {
@GET(NetworkConstant.DATA) // hear pass your api call
fun getData(): Call<List<Hero>>

}

为API值制作单独的网络类,如下所示...

class NetworkConstant {
companion object{
    const val DATA = "marvel"
}

}

当您调用API并获得响应后,可以使用以下代码:

 private fun getHeroData() {
    val dialog= ProgressDialog(mContext)
    showProgress(dialog)
    var apiInterface: ApiInterface = ApiClient.getClient()!!.create(ApiInterface::class.java)
    var hero: Call<List<Hero>>
    hero = apiInterface.getData()
    hero.enqueue(object : Callback<List<Hero>> {
        override fun onFailure(call: Call<List<Hero>>?, t: Throwable?) {
            closeDialog(dialog)
            Toast.makeText(mContext, t?.message, Toast.LENGTH_SHORT).show()
            Log.d("Error:::",t?.message)
        }

        override fun onResponse(call: Call<List<Hero>>?, response: Response<List<Hero>>?) {
           mHeroDataList.clear()
            if (response != null && response.isSuccessful && response.body() != null) {
                closeDialog(dialog)
                mHeroDataList .addAll(response.body()!!)
                setAdapter(mHeroDataList)
            }
        }

    })
}

0
这里我发布我的代码。

异步任务函数

    inner class GetAsyncTask : AsyncTask<String, String, String>() {

        override fun onPreExecute() {
            // Before doInBackground
        }

        override fun doInBackground(vararg urls: String?): String {
            var urlConnection: HttpURLConnection? = null

            try {
                val url = URL(urls[0])

                urlConnection = url.openConnection() as HttpURLConnection


                var inString = streamToString(urlConnection.inputStream)

                publishProgress(inString)
            } catch (ex: Exception) {

            } finally {
                if (urlConnection != null) {
                    urlConnection.disconnect()
                }
            }

            return " "
        }

        override fun onProgressUpdate(vararg values: String?) {
            try {
                var json = JSONObject(values[0])

                val query = json.getJSONObject("query")
                val results = query.getJSONObject("results")
                val channel = results.getJSONObject("channel")

                val location = channel.getJSONObject("location")
                val city = location.get("city")
                val country = location.get("country")

                val humidity = channel.getJSONObject("atmosphere").get("humidity")
            val condition = channel.getJSONObject("item").getJSONObject("condition")
            val temp = condition.get("temp")
            val text = condition.get("text")

            tvWeatherInfo.text =
                    "Location: " + city + " - " + country + "\n" +
                            "Humidity: " + humidity + "\n" +
                            "Temperature: " + temp + "\n" +
                            "Status: " + text

        } catch (ex: Exception) {

        }
    }

    override fun onPostExecute(result: String?) {
        // Done
    }


}

streamToString(流转字符串)
fun streamToString(inputStream: InputStream): String {

    val bufferReader = BufferedReader(InputStreamReader(inputStream))
    var line: String
    var result = ""

    try {
        do {
            line = bufferReader.readLine()
            if (line != null) {
                result += line
            }
        } while (line != null)
        inputStream.close()
    } catch (ex: Exception) {

    }

    return result
}

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接