Saturday 11 August 2018

All You Need To Know About Efficient Network Access And Sending JSON object Using OkHttp

ad300
Advertisement
Sometime you may need to POST the events to the endpoint based on your project needs. There are various APIs available to request and get the response from the events in the market but when I came across OkHttp I started loving the simplicity of it.
It is one of the APIs that is very easy to understand and easy to use. OkHttp is mostly used to exchange data & media. Doing HTTP efficiently using it makes your data load faster and saves bandwidth.



Below are some of the features of OkHttp:
  1. Connection pooling reduces request latency
  2. It will silently recover from common connection problems
  3. If your service request has multiple IP addresses OkHttp will attempt alternate addresses if the first connection fails.
  4. OkHttp initiates new connections with modern TLS features (SNI, ALPN), and falls back to TLS 1.0 if the handshake fails.

Now why to wait, let's see how we use the OkHttp in our Code. So as part of this tutorial, I am performing below operations:

  1. Send Login Event
  2. CreateSession Event
  3. Publish Event
Sending Login Event:  You can create your own SampleUtil and add login method to that class. The method below is calling a login() method of SampleUtil. Login method will return the response object which will be stored in the reference variable "response". This variable later can be used to validate the response code which in this case is 200.  You need to fetch the "jwt" from the response which you will need to Create a Session event later.

public void iSendLoginRequest() throws Throwable {
    try {
        Response response = SampleUtil.login("http://loginurl:8080", jsonBody);
        assertEquals(responseCode, response.code());
        String responseBody = response.body().string();
        JSONObject object = new JSONObject(responseBody);
        String jwtToken = object.getString("jwt");
    } catch (Exception e) {
        System.out.println(e.getMessage());
    }
}
SampleUtil.java Code:
public static Response login(String loginUrl, String jsonBody) {
     try {
         RequestBody body = RequestBody.create(MediaType.parse("application/json; charset=utf-8"), jsonBody);

         OkHttpClient client = new OkHttpClient();
         okhttp3.Request request = new okhttp3.Request.Builder()
                 .url(loginUrl)
                 .post(body)
                 .build();

         return client.newCall(request).execute();
     } catch (Exception e) {
         e.printStackTrace();
     }
     return null;
 }
Performing Create Session Event: createSession() takes the URL, JSON body and JWT as the parameters and method will return the response object which will be stored in the reference variable "response". This variable later can be used to validate the response code which in this case is 200. Along with that, you need to fetch the "sessionId" from the response which you need to Publish the event later.

public void iCreateSessionRequest() throws Throwable {
    try {
        Response response = SampleUtil.createSession("http://createsessionurl:8080",jsonBody, jwtToken);
        assertEquals(responseCode, response.code());
        String responseBody = response.body().string();
        JSONObject object = new JSONObject(responseBody);
        sessionId = object.getString("sessionId");

    } catch (Exception e) {
        e.printStackTrace();
    }
}

SampleUtil.java Code:
 public static Response createSession(String createSessionUrl, String jsonBody, String jwt) {
    try {
        RequestBody body = RequestBody.create(MediaType.parse("application/json; charset=utf-8"), jsonBody);
        OkHttpClient client = new OkHttpClient();
        okhttp3.Request request = new okhttp3.Request.Builder()
                .url(createSessionUrl)
                .addHeader("Authorization", "Bearer " + jwt)
                .post(body)
                .build();

        return client.newCall(request).execute();

    } catch (Exception e) {
         e.printStackTrace();
    }
    return null;
}

Publishing the Event: publishEvent() takes the URL, JSON body and SESSION ID as the parameters and method will return the response object which will be stored in the reference variable "response". This variable later can be used to validate the response code which in this case is 200. Along with that, you need to fetch the "sessionId" from the response which you need to Publish the event later.

public void iPerformsAPublishEventRequest() throws Throwable {
    try {
        Response response = SampleUtil.publishEvent("http://publisheventurl:8080",jsonBody,sessionId);
        assertEquals(responseCode, response.code());
    } catch (Exception e) {
        System.out.println(e.getMessage());
    }
}

SampleUtil.java Code:
public static Response publishEvent(String url, String jsonBody, String sessionId) {
    try {
        RequestBody body = RequestBody.create(MediaType.parse("application/json; charset=utf-8"), jsonBody);

        OkHttpClient client = new OkHttpClient();
        okhttp3.Request request = new okhttp3.Request.Builder()
                .url(url)
                .post(body)
                .addHeader("sessionId", sessionId)
                .build();
        return client.newCall(request).execute();

    } catch (Exception e) {
        e.printStackTrace();
    }
    return null;
}
Share This
Previous Post
Next Post

Welcome to my blog, I am Subhash Junas, I have been working on Core Java, Ruby, Selenium, Cucumber and on various automation technologies from past couple of years. I love to work on new challenges, solving problems and obstacles.

0 comments: