Create a gist now

Instantly share code, notes, and snippets.

What would you like to do?
api caller with okhttp
import android.os.Handler;
import java.io.IOException;
import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;
/**
* Created by shogo on 2016/06/04.
*/
public abstract class ApiCaller {
private Handler mHandler = null;
ApiCaller () {
mHandler = new Handler();
}
public void callApi (String url) {
OkHttpClient client = new OkHttpClient();
Request request = new Request.Builder().url(url).build();
Call call = client.newCall(request);
call.enqueue(new Callback() {
@Override
public void onFailure(Call call, IOException e) {}
@Override
public void onResponse(Call call, Response response) throws IOException {
final String responseBody = response.body().string();
mHandler.post(new Runnable() {
@Override
public void run() {
onResponseReceived(responseBody);
}
});
}
});
}
public abstract void onResponseReceived (String responseBody);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment