Skip to content

Instantly share code, notes, and snippets.

@milaptank
Created June 25, 2016 11:57
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save milaptank/10831ad97254128dcc29bb09a2eb7bfa to your computer and use it in GitHub Desktop.
Save milaptank/10831ad97254128dcc29bb09a2eb7bfa to your computer and use it in GitHub Desktop.
package api;
import android.os.Handler;
import android.os.Looper;
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 org.json.JSONObject;
import java.io.IOException;
public class AsyncOkHttpClient {
private static final OkHttpClient SINGLETON = new OkHttpClient();
private AsyncOkHttpClient() {
}
public static void get(String url, Callback callback) {
Request request = new Request.Builder()
.url(url)
.get()
.build();
execute(request, callback);
}
public static void post(String url, JSONObject json, Callback callback) {
RequestBody requestBody = RequestBody.create(
MediaType.parse("application/json"), json.toString());
Request request = new Request.Builder()
.url(url)
.post(requestBody)
.build();
execute(request, callback);
}
private static void execute(final Request request, final Callback callback) {
final Handler handler = new Handler(Looper.getMainLooper());
SINGLETON.newCall(request).enqueue(new com.squareup.okhttp.Callback() {
@Override
public void onFailure(final Request request, final IOException e) {
handler.post(new Runnable() {
@Override
public void run() {
callback.onFailure(null, e);
}
});
}
@Override
public void onResponse(final Response response) throws IOException {
handler.post(new Runnable() {
@Override
public void run() {
if (!response.isSuccessful()) {
callback.onFailure(response, null);
return;
}
handler.post(new Runnable() {
@Override
public void run() {
try {
response.body().string();
} catch (IOException e) {
e.printStackTrace();
}
}
});
callback.onSuccess(response);
}
});
}
});
}
public interface Callback {
public void onFailure(Response response, Throwable throwable);
public void onSuccess(Response response);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment