import java.io.IOException; import okhttp3.Call; import okhttp3.Callback; import okhttp3.OkHttpClient; import okhttp3.Request; import okhttp3.Response; public class OkHttpAsynchronous { public static void main(String[] args) { // avoid creating several instances, should be singleton OkHttpClient client = new OkHttpClient(); // creating a request object Request request = new Request.Builder() .url("https://api.quotable.io/random") .build(); // asynchronous network call client.newCall(request).enqueue(new Callback() { @Override public void onFailure(Call call, IOException e) { e.printStackTrace(); } @Override public void onResponse(Call call, final Response response) throws IOException { if (!response.isSuccessful()) { throw new IOException("Unexpected code " + response); } else { // receiving json body System.out.println(response.body().string()); } } }); } }
Preview:
downloadDownload PNG
downloadDownload JPEG
downloadDownload SVG
Tip: You can change the style, width & colours of the snippet with the inspect tool before clicking Download!
Click to optimize width for Twitter