OkHttpAsynchronous
Tue Apr 05 2022 11:05:47 GMT+0000 (Coordinated Universal Time)
Saved by
@oliversinz
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());
}
}
});
}
}
content_copyCOPY
Comments