api caller with okhttp
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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