Httpclient kotlin post запрос

Send Post request using Android 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. Here I’m posting my code Solution 3: you have also used retrofit 2.0 add dependency in gradle file like below . show every api call and data into log cat add below depencey .. and after make one class for api set up like below .. > then after make interface to call different type of api like below . > make sparate class for network for api value like bellow .. > then after when you call to api and getting response that time used below code ..

Send Post request using Android Kotlin

I’m trying to send a POST request using Kotlin in Android. I need to use Volley and I need authentication with a bearer token. I don’t know how to send the bearer token together with the post request.

val queue = Volley.newRequestQueue(this) val parameters: MutableMap = HashMap() parameters.put("token_name", "app"); val strReq: StringRequest = object : StringRequest( Method.POST, "https://url.com", Response.Listener < response ->try < val responseObj = JSONObject(response) val val token = responseObj.getString("name") val tipo = responseObj.getString("email") >catch (e: Exception) < // caught while parsing the response >>, Response.ErrorListener < volleyError ->>) 

You can override the volley’s request method:

public void requestWithSomeHttpHeaders(Context context) < RequestQueue queue = Volley.newRequestQueue(context); String url = "http://www.somewebsite.com"; StringRequest getRequest = new StringRequest(Request.Method.POST, url, new Response.Listener() < @Override public void onResponse(String response) < // response try < JSONObject responseObj = new JSONObject(response); int String token = responseObj.getString("name"); String tipo = responseObj.getString("email"); >catch (Exception e) < // caught while parsing the response >> >, new Response.ErrorListener() < @Override public void onErrorResponse(VolleyError error) < // TODO Auto-generated method stub Log.d("ERROR", "error =>" + error.toString()); > > ) < @Override public MapgetHeaders() throws AuthFailureError < Mapparams = new HashMap(); //insert your bearer token here params.put("bearer token", "xxxxxx"); return params; > >; queue.add(getRequest); > 

Of course, you can read this post as a refer.

How can I call post request with body in android tor client, You can send a multipart/form-data request using an instance of the MultiPartFormDataContent class for a body or the

Introduction to HTTP/REST

Being able to interact with data from the internet is an important skill for Android developers. In Duration: 10:27

HTTP Requests in Kotlin with a Ktor Client and Kotlinx Serialization

This tutorial consists of three parts: 1. An API for our HTTP Requests 2. Setting up Ktor 3
Duration: 6:22

Читайте также:  Python округлить число вниз

5 Simple Steps : Post Request in android kotlin using retrofit

A Post request is a request from the client to send some data to the post request retrofit Duration: 10:53

What is the simplest way to make a post request in Kotlin for Android app

The question about post requests in android has been asked before, but all the solutions I’ve tried have not worked properly. On top of that, a lot of them seem to be overly complicated as well. All I wish to do is make a post to a specific sight with a few body parameters. Is there any simple way to do that?

Let me explain my request calling structure using Retrofit.

build.gradle(app)

// Retrofit + GSON implementation 'com.squareup.okhttp3:logging-interceptor:4.4.0' implementation "com.squareup.retrofit2:retrofit:2.9.0" implementation "com.squareup.retrofit2:converter-gson:2.9.0" 

ApiClient.kt

object ApiClient < private const val baseUrl = ApiInterface.BASE_URL private var retrofit: Retrofit? = null private val dispatcher = Dispatcher() fun getClient(): Retrofit? < val logging = HttpLoggingInterceptor() if (BuildConfig.DEBUG) logging.level = HttpLoggingInterceptor.Level.BODY else logging.level = HttpLoggingInterceptor.Level.NONE if (retrofit == null) < retrofit = Retrofit.Builder() .client(OkHttpClient().newBuilder().readTimeout(120, TimeUnit.SECONDS) .connectTimeout(120, TimeUnit.SECONDS).retryOnConnectionFailure(false) .dispatcher( dispatcher ).addInterceptor(Interceptor < chain: Interceptor.Chain? ->val newRequest = chain?.request(). newBuilder() return@Interceptor chain.proceed(newRequest.build()) >).addInterceptor(logging).build() ) .baseUrl(baseUrl) .addConverterFactory(GsonConverterFactory.create()) .build() > return retrofit > > 

ApiClient will be used to initialize Retrofit singleton object, also initialize logging interceptors so you can keep track of the requests and responses in the logcat by using the keyword ‘okhttp’.

SingleEnqueueCall.kt

object SingleEnqueueCall < var retryCount = 0 lateinit var snackbar: Snackbar fun callRetrofit( activity: Activity, call: Call, apiName: String, isLoaderShown: Boolean, apiListener: IGenericCallBack ) < snackbar = Snackbar.make( activity.findViewById(android.R.id.content), Constants.CONST_NO_INTERNET_CONNECTION, Snackbar.LENGTH_INDEFINITE ) if (isLoaderShown) activity.showAppLoader() snackbar.dismiss() call.enqueue(object : Callback< override fun onResponse(call: Call, response: Response) < hideAppLoader() if (response.isSuccessful) < retryCount = 0 apiListener.success(apiName, response.body()) >else < when < response.errorBody() != null ->try < val json = JSONObject(response.errorBody(). string()) Log.e("TEGD", "JSON==>" + response.errorBody()) Log.e("TEGD", "Response Code==> " + response.code()) val error = json.get("message") as String apiListener.failure(apiName, error) > catch (e: Exception) < e.printStackTrace() Log.e("TGED", "JSON==>" + e.message) Log.e("TGED", "Response Code==> " + response.code()) apiListener.failure(apiName, Constants.CONST_SERVER_NOT_RESPONDING) > else -> < apiListener.failure(apiName, Constants.CONST_SERVER_NOT_RESPONDING) return >> > > override fun onFailure(call: Call, t: Throwable) < hideAppLoader() val callBack = this if (t.message != "Canceled") < Log.e("TGED", "Fail==>" + t.localizedMessage) if (t is UnknownHostException || t is IOException) < snackbar.setAction("Retry") < snackbar.dismiss() enqueueWithRetry(activity, call, callBack, isLoaderShown) >snackbar.show() apiListener.failure(apiName, Constants.CONST_NO_INTERNET_CONNECTION) > else < retryCount = 0 apiListener.failure(apiName, t.toString()) >> else < retryCount = 0 >> >) > fun enqueueWithRetry( activity: Activity, call: Call, callback: Callback, isLoaderShown: Boolean ) < activity.showAppLoader() call.clone().enqueue(callback) >> 

SingleEnqueueCall will be used for calling the retrofit, it is quite versatile, written with onFailure() functions and by passing Call to it, we can call an API along with ApiName parameter so this function can be used for any possible calls and by ApiName , we can distinguish in the response that which API the result came from.

Читайте также:  Python явное объявление переменных

Constants.kt

ApiInterface.kt

interface ApiInterface < companion object < const val BASE_URL = "URL_LINK" >@POST(Constants.USER_REGISTER) fun userRegister(@Body userRegisterRequest: UserRegisterRequest): Call > 

UserRegisterRequest.kt

data class UserRegisterRequest( val Email: String, val Password: String ) 

UserRegisterResponse.kt

data class UserRegisterResponse( val Message: String, val Code: Int ) 

IGenericCallBack.kt

interface IGenericCallBack

MyApplication.kt

class MyApplication : Application() < companion object < lateinit var apiService: ApiInterface >override fun onCreate() < super.onCreate() apiService = ApiClient.getClient(). create(ApiInterface::class.java) >> 

MyApplication is the application class to initialize Retrofit at the launch of the app.

AndroidManifest.xml

You have to write above tag in AndroidManifest inside Application tag.

MainActivity.kt

class MainActivity : AppCompatActivity(), IGenericCallBack < private lateinit var binding: ActivityMainBinding override fun onCreate(savedInstanceState: Bundle?) < super.onCreate(savedInstanceState) binding = ActivityMainBinding.inflate(layoutInflater) setContentView(binding.root) val call = MyApplication.apiService.userRegister(UserRegisterRequest(email, password)) SingleEnqueueCall.callRetrofit(this, call, Constants.USER_REGISTER, true, this) >override fun success(apiName: String, response: Any?) < val model = response as UserRegisterResponse >override fun failure(apiName: String, message: String?) < if (message != null) < showToastMessage(message) >> > 

Firstly, we create a call object by using the API defined in ApiInterface and passing the parameters (if any). Then using SingleEnqueueCall , we pass the call to the retrofit along with ApiName and the interface listener IGenericCallBack by using this . Remember to implement it to respective activity or fragment as above.

Secondly, you will have the response of the API whether in success() or failure() function overriden by IGenericCallBack

P.S: You can differentiate which API got the response by using the ApiName parameter inside success() function.

override fun success(apiName: String, response: Any?) < when(ApiName) < Constants.USER_REGISTER -> < val model = response as UserRegisterResponse >> > 

The whole concept is to focus on reusability, now every API call has to create a call variable by using the API’s inside ApiInterface then call that API by SingleEnqueueCall and get the response inside success() or failure() functions.

Kotlin HTTP Client Configuration, Http is the data communication found in the whole world. We are using the ktor framework to make an http client request in kotlin, which helps to build the

How to HTTP request by POST method with Kotlin [duplicate]

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

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.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") >> > 
 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 >> 
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 > 

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 .

Читайте также:  Поле загрузки файлов, которое мы заслужили

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

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

How to make a HTTP/POST request in Kotlin (Android) to simple, If you want to connect of server for sending requests (POST and GET) then follow this code public void callApi(String urls,String calledFor)

Источник

Оцените статью