Skip to content

Instantly share code, notes, and snippets.

@manniru
Forked from mohsinknsd/RESTClient.java
Created May 3, 2022 14:04
Show Gist options
  • Select an option

  • Save manniru/0d60c6f8eeb46a487a4bc545d1d2e70c to your computer and use it in GitHub Desktop.

Select an option

Save manniru/0d60c6f8eeb46a487a4bc545d1d2e70c to your computer and use it in GitHub Desktop.
A REST Api client to deal get and post requests using OkHttp 3.
import android.content.Context;
import android.support.annotation.Nullable;
import android.util.Log;
import java.io.IOException;
import java.util.concurrent.TimeUnit;
import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.Interceptor;
import okhttp3.MediaType;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;
import okhttp3.ResponseBody;
import okio.Buffer;
/**
* A rest api client to handle all network calls (get/post) in the application. {@code requestData} method
* will take a {@link Callback} implementation and this class is intercepting the server response using
* another {@link Callback}. But finally results will be published through user defined {@link Callback}.
*
* @author Mohsin Khan
* @date May 17 2016
*/
public class RESTClient implements Interceptor {
public static final String GET_API = "maps/api/geocode/json?address=jaipur";
public static final String POST_API = "post/request/url";
/**
* In my case, all apis contains same media type that is {@code application/x-www-form-urlencoded}
*/
private static MediaType mediaType = MediaType.parse("application/x-www-form-urlencoded");
/**
* Factory for calls, which can be used to send HTTP requests and read their responses.
* Most applications can use a single OkHttpClient for all of their HTTP requests,
* benefiting from a shared response cache, thread pool, connection re-use, etc.
*/
private static OkHttpClient client = new OkHttpClient.Builder()
.connectTimeout(40, TimeUnit.SECONDS)
.writeTimeout(40, TimeUnit.SECONDS)
.readTimeout(60, TimeUnit.SECONDS)
.retryOnConnectionFailure(true)
.addInterceptor(new RESTClient())
.build();
/**
* A private and default constructor to initialize the current class as a interceptor for all http calls.
* Without it, the class wont work.
*/
private RESTClient() {
}
/**
* Method will request data to the server and publish results in the callback provided in arguments.
*
* @param context application/activity context to get shared preferences
* @param url api/resource url
* @param body request body separated by '&'
* @param callback implementation of callback class to get results
* @return currently initiated call
*/
public static Call requestData(Context context, String url, @Nullable String body, Callback callback) {
SPUtils spUtils = new SPUtils(context);
Request.Builder builder = new Request.Builder().url(spUtils.getHostAddress() + url);
if (body != null)
builder.post(RequestBody.create(mediaType, body))
.addHeader("token", spUtils.getString(SPUtils.ACCESS_TOKEN));
Call call = client.newCall(builder.build());
call.enqueue(callback);
return call;
}
@Override
public Response intercept(Chain chain) throws IOException {
try {
// Logging request url
Request request = chain.request();
Log.e("--- ", new String(new char[100]).replace("\0", "—"));
Log.e("URL ", request.url().toString());
// Logging request body part in case of post requests
Buffer buffer = new Buffer();
RequestBody requestBody = request.body();
if (requestBody != null) {
requestBody.writeTo(buffer);
String bdy = buffer.readUtf8().replace("=", ":");
if (!bdy.trim().equals(""))
Log.e("BDY ", bdy);
buffer.close();
}
// Logging header in of post requests
String headers = request.headers().toString().replace("\n", "&").replace(": ", ":");
if (!headers.trim().equals("")) {
Log.e("HDR ", headers.substring(0, headers.length() - 1));
}
// Now Checking the results
// TODO: Handle any common case here
// TODO: Like auto refresh token if expired
// And returning response back to interceptor
Response response = chain.proceed(chain.request());
ResponseBody body = response.body();
String content = body.string();
Log.e("RES ", content.trim().equals("") ? "Empty Response" : content);
body.close();
return response.newBuilder().body(ResponseBody.create(response.body().contentType(), content)).build();
} catch (Exception e) {
Log.e("ERR ", e.getClass().getName() + " : " + e.getMessage());
e.printStackTrace();
}
return chain.proceed(chain.request());
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment