这个问题在这里已经有答案了
:
Kotlin中的HTTP请求
(11个答案)
两年前就关门了。
我是一个新的kotlin开发人员。请教我如何在Kotlin中使用httpRequest。
问题-如果我想请求API服务,并且我必须使用post方法发送带有json对象的请求体,我该如何编写??
谢谢你的帮助。
发布于 2018-03-09 15:42:51
我在这里发布我的代码
异步任务函数
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
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
}
发布于 2018-03-09 18:30:23
您还在gradle文件中使用了retrofit 2.0 add dependency,如下所示……
compile 'com.squareup.retrofit2:retrofit:2.3.0'
将每个api调用和数据显示到日志猫添加到下面的depencey中。
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>
}
为网络的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>
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)
}
}
})
}
https://stackoverflow.com/questions/49188722
复制相似问题