Skip to content

Instantly share code, notes, and snippets.

@shogonir
Created June 4, 2016 03:26
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 shogonir/41fd2cc670755aeff5a21cef893b7112 to your computer and use it in GitHub Desktop.
Save shogonir/41fd2cc670755aeff5a21cef893b7112 to your computer and use it in GitHub Desktop.
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