Skip to content

Instantly share code, notes, and snippets.

@jalvarado91
Last active September 15, 2017 13:46
Show Gist options
  • Save jalvarado91/8dc04a3e41d5fe5849cc to your computer and use it in GitHub Desktop.
Save jalvarado91/8dc04a3e41d5fe5849cc to your computer and use it in GitHub Desktop.
Ok Http Callback Wrap
package com.example.jalvarado.mlsview.utils;
import com.squareup.okhttp.Callback;
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 java.io.IOException;
import okio.BufferedSink;
public class HttpUtil {
private OkHttpClient client;
private Request.Builder builder;
public HttpUtil() {
client = new OkHttpClient();
builder = new Request.Builder();
}
public void get(String url, HttpCallback callback) {
call("GET", url, callback);
}
public void post(String url, HttpCallback cb) {
call("POST", url, cb);
}
private void call(String method, String url, final HttpCallback callback){
Request request = builder.url(url).method(method, method.equals("GET") ? null : new RequestBody() {
// don't care much about request body
@Override
public MediaType contentType() {
return null;
}
@Override
public void writeTo(BufferedSink sink) throws IOException {
}
}).build();
client.newCall(request).enqueue(new Callback() {
@Override
public void onFailure(Request request, IOException e) {
callback.onFailure(null, e);
}
@Override
public void onResponse(Response response) throws IOException {
if (!response.isSuccessful()) {
callback.onFailure(response, null);
return;
}
callback.onSuccess(response);
}
});
}
public interface HttpCallback {
public void onFailure(Response response, IOException e);
public void onSuccess(Response response);
}
}
mHttpUtil.get(searchUrl, new HttpUtil.HttpCallback() {
@Override
public void onFailure(Response response, IOException e) {
}
@Override
public void onSuccess(Response response) {
try {
String jsonData = response.body().string();
mDetailedListing = mListingViewPresenter.getDetailedListing(jsonData);
runOnUiThread(new Runnable() {
@Override
public void run() {
fillRestOfDetails();
}
});
Log.v(TAG, jsonData);
} catch (IOException | JSONException e) {
e.printStackTrace();
}
}
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment