Skip to content

Instantly share code, notes, and snippets.

@Antarix
Last active September 2, 2016 12:28
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save Antarix/cc4db017b0c8829dd00ddd09ac933d52 to your computer and use it in GitHub Desktop.
Save Antarix/cc4db017b0c8829dd00ddd09ac933d52 to your computer and use it in GitHub Desktop.
Helper class for OkHttp http://square.github.io/okhttp/

#Helper Class for using OkHttp

###Usage

Added OkHttp depandancy

Call this from backround thread or AsyncTask ApiCall.getJsonFromUrl(getString(R.string.api_url));

import android.util.Log;
import org.json.JSONObject;
import java.io.IOException;
import okhttp3.MediaType;
import okhttp3.OkHttpClient;
import okhttp3.RequestBody;
import okhttp3.Response;
import okhttp3.Request;
/**
* Created by Antarix on 11/08/16.
*/
public class ApiCall {
private static int GET = 1;
private static int POST = 2;
private static final MediaType JSON = MediaType.parse("application/json; charset=utf-8");
public static JSONObject getJsonFromUrl(String url){
return getJson(url,GET,null);
}
public static JSONObject postJsonFromUrl(String url,String jsonString){
return getJson(url,POST,jsonString);
}
private static JSONObject getJson(String url,int method,String jsonStringParams){
JSONObject json = null;
// try parse the string to a JSON object
try {
String jsonString = makeServiceCall(url, method, jsonStringParams);
if (jsonString != null) {
json = new JSONObject(jsonString);
}
return json;
} catch (Exception e) {
Log.e("ApiCall", "Error parsing data " + e.toString());
return json;
}
}
private static String makeServiceCall(String url,int method, String jsonStringParams) throws IOException {
OkHttpClient client = new OkHttpClient();
Request request;
if (method == POST){
RequestBody body = RequestBody.create(JSON, jsonStringParams);
request = new Request.Builder()
.url(url)
.post(body)
.build();
}else{
request = new Request.Builder()
.url(url)
.build();
}
Response response = client.newCall(request).execute();
return response.body().string();
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment