Last updated on August 28th, 2020 at 04:42 pm
In this post I will explain to you how we can send GET And POST request using OKHttp in Android Application. In my last post, I will explain how we can send GET and Post Request using Volley. OKHttp and Http & Http/2 client is widely used in android and java applications to create a request to the server. In this post, I am going to explain some most useful feature of OKHttp.
OKHttp is the modern way to make and exchange data and media over HTTP network. It helps to load data faster, efficiently and also saves bandwidth.
- HTTP/2 support allows all requests to the same host to share a socket.
- Connection pooling reduces request latency (if HTTP/2 isn’t available).
- Transparent GZIP shrinks download sizes.
- Response caching avoids the network completely for repeat requests.
OkHttp is very easy to use. Its request/response API is designed with fluent builders and immutability. It supports both synchronous blocking calls and async calls with callbacks. Now we can start creating our android application.
Step 1. Create a new Android project in Android Studio and name it what you like.
Step 2. Now we need to add dependencies to our Android project add below code and sync
implementation 'com.squareup.okhttp3:okhttp:3.11.0'
Step 3. Add internet permission in manifest file
<uses-permission android:name="android.permission.INTERNET"></uses-permission>
Now I can create a simple method in which In which I can explain how we can use OkHttp to send the request.
public void getHttpResponse() throws IOException { String url = "https://cakeapi.trinitytuts.com/api/listuser"; OkHttpClient client = new OkHttpClient(); Request request = new Request.Builder() .url(url) .header("Accept", "application/json") .header("Content-Type", "application/json") .build(); // Response response = client.newCall(request).execute(); // Log.e(TAG, response.body().string()); client.newCall(request).enqueue(new Callback() { @Override public void onFailure(Call call, IOException e) { String mMessage = e.getMessage().toString(); Log.w("failure Response", mMessage); //call.cancel(); } @Override public void onResponse(Call call, Response response) throws IOException { String mMessage = response.body().string(); Log.e(TAG, mMessage); } }); }
When we call above method it returns a list of the user. This method makes an Asynchronous call to the server because if you make the Synchronous call using Response method it will through NetworkOnMainThread exception on response.body() error so I prefer to use Async call.
Response response = client.newCall(request).execute();
In above method, I also add header because in my server API it is required to send header type and it is very easy in OKHttp to set header and Auth Token in it I further explain how to do that. And also to make Async call we need to add newCall() and enqueue() to run and get callback response in it.
Step 4. In this step, I will explain to you how we can post data to the server in OKHttp if you want to send get request please check function in Step 3 I created. To create a post request we need to create a JSON Object and after that, we need to convert JSON to string and post it to the server it was a very easy task.
public void postRequest() throws IOException { MediaType MEDIA_TYPE = MediaType.parse("application/json"); String url = "https://cakeapi.trinitytuts.com/api/add"; OkHttpClient client = new OkHttpClient(); JSONObject postdata = new JSONObject(); try { postdata.put("username", "aneh"); postdata.put("password", "12345"); } catch(JSONException e){ // TODO Auto-generated catch block e.printStackTrace(); } RequestBody body = RequestBody.create(MEDIA_TYPE, postdata.toString()); Request request = new Request.Builder() .url(url) .post(body) .header("Accept", "application/json") .header("Content-Type", "application/json") .build(); client.newCall(request).enqueue(new Callback() { @Override public void onFailure(Call call, IOException e) { String mMessage = e.getMessage().toString(); Log.w("failure Response", mMessage); //call.cancel(); } @Override public void onResponse(Call call, Response response) throws IOException { String mMessage = response.body().string(); Log.e(TAG, mMessage); } }); }
Above method is same as we create method on step 3 but in this, we create JSON Object and pass that object to RequestBody and the add RequestBody in post method where we create actual request.
Complete Code of OKHttp Example:-
Screen Layout Code
<?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:app="http://schemas.android.com/apk/res-auto" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" android:orientation="vertical" tools:context=".MainActivity"> <Button android:id="@+id/loadApi" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="Load Api"/> <Button android:id="@+id/postReq" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="Post Request" /> </LinearLayout>
Here is MainActivity Code
Note please change username and password when you run this example.
package com.trinityokhttp; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.util.Log; import android.view.View; import android.widget.Button; import org.json.JSONException; import org.json.JSONObject; import java.io.IOException; import okhttp3.Call; import okhttp3.Callback; import okhttp3.MediaType; import okhttp3.OkHttpClient; import okhttp3.Request; import okhttp3.RequestBody; import okhttp3.Response; public class MainActivity extends AppCompatActivity { private static final String TAG = "Response"; Button loadApi, postReq; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); loadApi = (Button)findViewById(R.id.loadApi); postReq = (Button)findViewById(R.id.postReq); loadApi.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { try { getHttpResponse(); } catch (IOException e) { e.printStackTrace(); } } }); postReq.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { try { postRequest(); } catch (IOException e) { e.printStackTrace(); } } }); } public void getHttpResponse() throws IOException { String url = "https://cakeapi.trinitytuts.com/api/listuser"; OkHttpClient client = new OkHttpClient(); Request request = new Request.Builder() .url(url) .header("Accept", "application/json") .header("Content-Type", "application/json") .build(); // Response response = client.newCall(request).execute(); // Log.e(TAG, response.body().string()); client.newCall(request).enqueue(new Callback() { @Override public void onFailure(Call call, IOException e) { String mMessage = e.getMessage().toString(); Log.w("failure Response", mMessage); //call.cancel(); } @Override public void onResponse(Call call, Response response) throws IOException { String mMessage = response.body().string(); Log.e(TAG, mMessage); } }); } public void postRequest() throws IOException { MediaType MEDIA_TYPE = MediaType.parse("application/json"); String url = "https://cakeapi.trinitytuts.com/api/add"; OkHttpClient client = new OkHttpClient(); JSONObject postdata = new JSONObject(); try { postdata.put("username", "aneh1234"); postdata.put("password", "12345"); } catch(JSONException e){ // TODO Auto-generated catch block e.printStackTrace(); } RequestBody body = RequestBody.create(MEDIA_TYPE, postdata.toString()); Request request = new Request.Builder() .url(url) .post(body) .header("Accept", "application/json") .header("Content-Type", "application/json") .build(); client.newCall(request).enqueue(new Callback() { @Override public void onFailure(Call call, IOException e) { String mMessage = e.getMessage().toString(); Log.w("failure Response", mMessage); //call.cancel(); } @Override public void onResponse(Call call, Response response) throws IOException { String mMessage = response.body().string(); Log.e(TAG, mMessage); } }); } }
Hope this post helps you 🙂