package com.mycompany.api.consumer; import okhttp3.HttpUrl; import okhttp3.OkHttpClient; import okhttp3.Request; import okhttp3.Response; public class OkHttpSynchronous { public static void main(String[] args) throws Exception { // avoid creating several instances, should be singleton OkHttpClient client = new OkHttpClient(); // optional: url parameters HttpUrl.Builder urlBuilder = HttpUrl.parse("https://api.github.help").newBuilder(); urlBuilder.addQueryParameter("v", "1.0"); urlBuilder.addQueryParameter("user", "vogella"); String url = urlBuilder.build().toString(); // creating a request object Request request = new Request.Builder() .url("https://api.quotable.io/random") .build(); // optional: headers Request authorizedRequest = new Request.Builder() .url("https://the-cocktail-db.p.rapidapi.com/random.php") .get() .addHeader("X-RapidAPI-Host", "the-cocktail-db.p.rapidapi.com") .addHeader("X-RapidAPI-Key", "SIGN-UP-FOR-KEY") .build(); // synchronous network call Response response = client.newCall(request).execute(); // 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