Android OkHttp Post and Get Request Tutorial

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.

Don't Miss

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

6 COMMENTS

  1. I know not many people have not seen this post made by you guys but this has been extremely helpful. I am creating a very specific app and tried a lot of places and asked a lot of people for help on OkHttp. I created a Disqus account just to comment this. I am really lucky that I searched Google and clicked on this link – thank you so much for making this post.
    godspeed

LEAVE A REPLY

Please enter your comment!
Please enter your name here

564FansLike

Recent Posts

Concept of Session in Laravel Tutorial

Sessions are used to store details about the user throughout the requests. Laravel supplies various drivers like file, cookie, apc, array, Memcached, Redis, and database to handle session data. By default, file driver is used as a result of it's light-weight....

Laravel Url Generation Tutorial

Our web application revolves around routes and URLs. After all, they're what direct our users to our pages. At the end of the day, serving pages is what any web application should do. Our users may...

Concept of Laravel Views Tutorial

In MVC framework, the letter "V" stands for Views. It separates the application logic and presentation logic. Views are saved in resources/views listing. Generally, the view contains the HTML which might be served by the application.

Related Articles

Concept of Session in Laravel Tutorial

Sessions are used to store details about the user throughout the requests. Laravel supplies various drivers like file, cookie, apc, array, Memcached, Redis, and database to handle session data. By default, file driver is used as a result of it's light-weight....

Laravel Url Generation Tutorial

Our web application revolves around routes and URLs. After all, they're what direct our users to our pages. At the end of the day, serving pages is what any web application should do. Our users may...

Concept of Laravel Views Tutorial

In MVC framework, the letter "V" stands for Views. It separates the application logic and presentation logic. Views are saved in resources/views listing. Generally, the view contains the HTML which might be served by the application.
WP2Social Auto Publish Powered By : XYZScripts.com