In my Android application, I am using okHttp library. How can I send parameters to the server(api) using the okhttp library? currently I am using the following code to access the server now need to use the okhttp library.
this is the my code:
httpPost = new HttpPost("http://xxx.xxx.xxx.xx/user/login.json"); nameValuePairs = new ArrayList<NameValuePair>(2); nameValuePairs.add(new BasicNameValuePair("email".trim(), emailID)); nameValuePairs.add(new BasicNameValuePair("password".trim(), passWord)); httpPost = new HttpPost(url); httpPost.setEntity(new UrlEncodedFormEntity(nameValuePairs)); String response = new DefaultHttpClient().execute(httpPost, new BasicResponseHandler());
OkHttp Query Parameters ExampleBuilder urlBuilder = HttpUrl. parse("https://httpbin.org/get).newBuilder(); urlBuilder. addQueryParameter("website", "www.journaldev.com"); urlBuilder. addQueryParameter("tutorials", "android"); String url = urlBuilder.
Overview. OkHttp is a third-party library developed by Square for sending and receive HTTP-based network requests. It is built on top of the Okio library, which tries to be more efficient about reading and writing data than the standard Java I/O libraries by creating a shared memory pool.
For OkHttp 3.x, FormEncodingBuilder was removed, use FormBody.Builder instead
RequestBody formBody = new FormBody.Builder() .add("email", "[email protected]") .add("tel", "90301171XX") .build(); OkHttpClient client = new OkHttpClient(); Request request = new Request.Builder() .url(url) .post(formBody) .build(); Response response = client.newCall(request).execute(); return response.body().string();
private final OkHttpClient client = new OkHttpClient(); public void run() throws Exception { RequestBody formBody = new FormEncodingBuilder() .add("email", "[email protected]") .add("tel", "90301171XX") .build(); Request request = new Request.Builder() .url("https://en.wikipedia.org/w/index.php") .post(formBody) .build(); Response response = client.newCall(request).execute(); if (!response.isSuccessful()) throw new IOException("Unexpected code " + response); System.out.println(response.body().string()); }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With