Android OkHttp Post and Get Request Tutorial

0

In this tutorial, we will learn how to send HTTP Post & Get Request to server using OkHttp Library in Android Application.



Introduction

OkHttp is open source and it supports SPDY protocol. SPDY is the basis for HTTP 2.0 and allows multiple HTTP requests to be multiplexed over one socket connection.

We will create a connection between Android App and server at certain period then send or receive the data request from Android App to server. OkHttp is a part of Android platform to use all HTTP request.

Add Internet Permission

To Send POST and GET request to server, means to create connection between server and Android Application, we need to give Internet permission to Android Application. Open your Manifest file and below code:

<uses-permission android:name="android.permission.INTERNET" />

Add OkHttp Library

We need to add OkHttp libary in the dependency. Open build.gradle(Module:app) file and add following code:

dependencies {
  ...
    compile 'com.squareup.okhttp3:okhttp:3.4.1'
  ...
}

Create Object

To use OkHttp, we need to create OkHttpClient() object.

final OkHttpClient client = new OkHttpClient();

POST Request



We can post any thing from OkHttp like String, Json, XML. In this tutorial, we are sending JSON as a request and getting also JSON as a response. To send POST request we need to create RequestBody Object and Pass it into Request Object. In the RequestBody object, we will pass Media type and post data as a string. Request Object is used to build your URL, POST data, Header(We can set Authorization token).

public static final MediaType MEDIA_TYPE = MediaType.parse("application/json");
JSONObject postdata = new JSONObject();
try {
     postdata.put("UserName", "Abhay Anand");
     postdata.put("Email", "anand.abhay1910@gmail.com");
   } catch(JSONException e){
     // TODO Auto-generated catch block
     e.printStackTrace();
}

RequestBody body = RequestBody.create(MEDIA_TYPE, postdata.toString());

final Request request = new Request.Builder()
  .url("YOUR URL")
  .post(body)
  .addHeader("Content-Type", "application/json")
  .addHeader("Authorization", "Your Token")
  .addHeader("cache-control", "no-cache")
  .build();

GET Request

To send GET request, We need to create only Request Object to build your URL, POST data, Header(We can set Authorization token).

Request request = new Request.Builder()
    .url("Your URL")
    .get()
    .addHeader("Content-Type", "application/json")
    .addHeader("Authorization", "Your Token")
    .addHeader("cache-control", "no-cache")
    .build();

Synchronous Call

To make a synchronous call, use the Client to create a Call object and use the execute method.

Response response = client.newCall(request).execute();
String serverResponse = response.body().string();

Asynchronous Call

To make Asynchronous calls, also create a Call object but use the enqueue method.

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();
        if (response.isSuccessful()){
          try {
             JSONObject json = new JSONObject(mMessage);
             final String serverResponse = json.getString("Your Index");             
                  
          } catch (Exception e){
            e.printStackTrace();
          }

        }
   }
});

Final POST Request And Asyncronous Call

public class MainActivity extends AppCompatActivity {
   public static final MediaType MEDIA_TYPE = 
                             MediaType.parse("application/json");
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        
        final OkHttpClient client = new OkHttpClient();
        JSONObject postdata = new JSONObject();
        try {
            postdata.put("UserName", "Abhay Anand");
            postdata.put("Email", "anand.abhay1910@gmail.com");
        } catch(JSONException e){
           // TODO Auto-generated catch block
           e.printStackTrace();
        }

        RequestBody body = RequestBody.create(MEDIA_TYPE, 
                                 postdata.toString());

        final Request request = new Request.Builder()
             .url("YOUR URL")
             .post(body)
             .addHeader("Content-Type", "application/json")
             .addHeader("Authorization", "Your Token")
             .addHeader("cache-control", "no-cache")
             .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();
                if (response.isSuccessful()){
                   try {
                      JSONObject json = new JSONObject(mMessage);
                     final String serverResponse = json.getString("Your Index");             
                  
                   } catch (Exception e){
                       e.printStackTrace();
                }
            }
       }
   });
}