Tuesday, 22 December 2015

Using the OkHttp library for HTTP requests

Now we are going to see how to use OkHttp library for HTTP requests in our project. Using of okHTTP we can call the web service and can get the response from server. Download OKHTTP from the official site (From Here) and follow the steps.

Create one Async Task.

Async Task Class:-

package com.test.project.helper;

import java.util.concurrent.TimeUnit;

import org.json.JSONException;
import org.json.JSONObject;

import com.squareup.okhttp.MediaType;
import com.squareup.okhttp.OkHttpClient;
import com.squareup.okhttp.Request;
import com.squareup.okhttp.RequestBody;
import com.squareup.okhttp.Response;
import com.squareup.okhttp.Request.Builder;
import com.test.project.interfaces.AsyncResponseListener;

import android.os.AsyncTask;

public class WebServiceHelper extends AsyncTask<String, Void, String>{
private Builder requestBuilder = null;
private String requestURL = null;

private static final MediaType JSON = MediaType.parse("application/json; charset=utf-8");
//private static final MediaType OCTET_STREAM = MediaType.parse("application/octet-stream");
private static final MediaType JAVA_SERIALIZED_OBJECT = MediaType.parse("application/x-java-serialized-object");

OkHttpClient client = new OkHttpClient();
public AsyncResponseListener delegate = null;

public WebServiceHelper(String requestURL){
this.requestURL = requestURL;
this.requestBuilder = new Builder().url(requestURL);
}

protected String doInBackground(String... params) {
try {
Request request = requestBuilder.build();

System.out.println("Request URL: " + request.urlString());
System.out.println("Auth Token: " + request.header("auth_token"));

if(request.body() != null){
System.out.println("Data Type: " + request.body().contentType().toString());
}

client.setConnectTimeout(60, TimeUnit.SECONDS);
Response response = client.newCall(request).execute();
//System.out.println("response ==>"+response.body().string());
return response.body().string();      
}
catch (Exception e) {

System.out.println("Connection Exception:" + e.getLocalizedMessage());

//Create the JSON for response
JSONObject errorResponse = new JSONObject();
   try {
    //Creating JSON object for response_status key
    JSONObject response_status = new JSONObject();
    response_status.put("response_code", 1);
    response_status.put("response_message", "Failed");
   
    //Creating JSON object for response_data key
    JSONObject response_data = new JSONObject();
    response_data.put("error", "Unable to complete the request due to network connection error. Please try again.");
   
    errorResponse.put("response_status", response_status);
    errorResponse.put("response_data", response_data);
   
} catch (JSONException JSONexp) {
JSONexp.printStackTrace();
}
 
   return errorResponse.toString();
   }
}

protected void onPostExecute(String responseString) {
   // TODO: check this.exception
   // TODO: do something with the feed
System.out.println("Response: " + responseString);

delegate.processFinish(this.requestURL, responseString);
}

public void addHeader(String name, String value){
this.requestBuilder.addHeader(name, value);
}

public void setRequestBody(String requestData){
System.out.println("Request Body: " + requestData);
this.requestBuilder.post(RequestBody.create(JSON, requestData));
}

public void setRequestBody(byte[] requestData){
System.out.println("Request Body: " + requestData.toString());
this.requestBuilder.post(RequestBody.create(JAVA_SERIALIZED_OBJECT, requestData));
}
}

Create Interface for process Finish:-

package com.test.project.interfaces;

public interface AsyncResponseListener {

void processFinish(String requestURL, String response);

}

Main Class:-

Then In your main class implements AsyncResponseListener and call this method to call web service.


private ProgressDialog pdia;
private void WebCalls() {
pdia = new ProgressDialog(this);
       pdia.setMessage("Loading...");
       pdia.show();    

JSONObject requestObject = new JSONObject();
//mProgressHUD = ProgressHUD.show(this, getString(R.string.loading), true, false, this);
WebServiceHelper wsHelper = new WebServiceHelper("http://api.openweathermap.org/data/2.5/forecast?q=Chennai&APPID=1eefb31e8b29125236c49903fc5f2c3d");
wsHelper.addHeader("Content-Type",
"application/json");
wsHelper.setRequestBody(requestObject.toString());
wsHelper.delegate = this;
wsHelper.execute();
}

@Override
public void processFinish(String requestURL, String response) {
pdia.dismiss();
// TODO Auto-generated method stub
System.out.println("response==> "+response);
WheatherModel weather =new WheatherModel(response);
System.out.println("weather.getId()==> "+weather.getId());
}

That's all. Now you can call the web service using  WebCalls() method. Just Use this method for all the class where you want to call the web service.

No comments:

Post a Comment