How to HTTP request by POST method with Kotlin [du

2019-05-23 02:02发布

问题:

This question already has an answer here:

  • HTTP Request in Kotlin 9 answers

I'm new a kotlin dev. please teach me to use httpRequest in Kotlin.

Question - If I want to request to API service and I must to send request body with json object by use post method, How I write??

Thank for help.

回答1:

You can write your data using 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")
            }
        }

    }


回答2:

Here I'm posting my code

Async Task Function

    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
}


回答3:

you have also used retrofit 2.0 add dependency in gradle file like below ...

  compile 'com.squareup.retrofit2:retrofit:2.3.0'

show every api call and data into log cat add below depencey ..

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

and after make one class for api set up like below ..

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
    }
}

}

then after make interface to call different type of api like below ...

interface ApiInterface {
@GET(NetworkConstant.DATA) // hear pass your api call
fun getData(): Call<List<Hero>>

}

make sparate class for network for api value like bellow ..

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

}

then after when you call to api and getting response that time used below code ..

 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)
            }
        }

    })
}