首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >如何使用Kotlin通过POST方法进行HTTP请求[复制]

如何使用Kotlin通过POST方法进行HTTP请求[复制]
EN

Stack Overflow用户
提问于 2018-03-09 15:34:20
回答 2查看 31.3K关注 0票数 5

这个问题在这里已经有答案了

Kotlin中的HTTP请求

(11个答案)

两年前就关门了。

我是一个新的kotlin开发人员。请教我如何在Kotlin中使用httpRequest。

问题-如果我想请求API服务,并且我必须使用post方法发送带有json对象的请求体,我该如何编写??

谢谢你的帮助。

EN

回答 2

Stack Overflow用户

发布于 2018-03-09 15:42:51

我在这里发布我的代码

异步任务函数

代码语言:javascript
运行
复制
inner class GetAsyncTask : AsyncTask() {

        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

代码语言:javascript
运行
复制
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
}
票数 1
EN

Stack Overflow用户

发布于 2018-03-09 18:30:23

您还在gradle文件中使用了retrofit 2.0 add dependency,如下所示……

代码语言:javascript
运行
复制
compile 'com.squareup.retrofit2:retrofit:2.3.0'

将每个api调用和数据显示到日志猫添加到下面的depencey中。

代码语言:javascript
运行
复制
compile 'com.squareup.okhttp3:logging-interceptor:3.4.1'

在为api创建一个类之后,如下所示..

代码语言:javascript
运行
复制
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后,如下所示...

代码语言:javascript
运行
复制
interface ApiInterface {
@GET(NetworkConstant.DATA) // hear pass your api call
fun getData(): Call>

}

为网络的api值创建稀疏类,如下所示。

代码语言:javascript
运行
复制
class NetworkConstant {
companion object{
    const val DATA = "marvel"
}

}

然后,当您调用api并获得响应后,在下面的代码中使用该时间。

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

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

    })
}
票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/49188722

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档