我是一个新的kotlin开发者。请教我在Kotlin中使用httpRequest。
问题 - 如果我想请求API服务,我必须使用post方法发送带有json对象的请求体,我怎么写?
感谢您的帮助。
答案 0 :(得分:1)
您可以使用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.connectTimeout = 300000
connection.doOutput = true
val postData: ByteArray = message.toByteArray(StandardCharsets.UTF_8)
connection.setRequestProperty("charset", "utf-8")
connection.setRequestProperty("Content-lenght", 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 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")
}
}
}
答案 1 :(得分: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
}
答案 2 :(得分:0)
您还在gradle文件中使用了retrofit 2.0 add依赖项,如下所示......
compile 'com.squareup.retrofit2:retrofit:2.3.0'
显示每个api调用和数据到log cat add underncey ..
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
}
}
}
然后在make接口之后调用不同类型的api如下...
interface ApiInterface {
@GET(NetworkConstant.DATA) // hear pass your api call
fun getData(): Call<List<Hero>>
}
为api值制作网络的sparate类,如bellow ..
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)
}
}
})
}