В этой статье показано, как использовать библиотеку OkHttp для отправки HTTP-запросов GET/POST, и приведены некоторые часто используемые примеры.
P.S Протестировано с помощью OkHttp 4.2.2
com.squareup.okhttp3 okhttp 4.2.2
1. Синхронный Запрос На Получение
package com.mkyong.http; import okhttp3.Headers; import okhttp3.OkHttpClient; import okhttp3.Request; import okhttp3.Response; import java.io.IOException; public class OkHttpExample1 { // only one client, singleton, better puts it in a factory, // multiple instances will create more memory. private final OkHttpClient httpClient = new OkHttpClient(); public static void main(String[] args) throws IOException { OkHttpExample1 obj = new OkHttpExample1(); obj.sendGETSync(); } private void sendGETSync() throws IOException { Request request = new Request.Builder() .url("https://httpbin.org/get") .addHeader("custom-key", "mkyong") // add request headers .addHeader("User-Agent", "OkHttp Bot") .build(); try (Response response = httpClient.newCall(request).execute()) { if (!response.isSuccessful()) throw new IOException("Unexpected code " + response); // Get response headers Headers responseHeaders = response.headers(); for (int i = 0; i < responseHeaders.size(); i++) { System.out.println(responseHeaders.name(i) + ": " + responseHeaders.value(i)); } // Get response body System.out.println(response.body().string()); } } }
2. Асинхронный Запрос На Получение
package com.mkyong.okhttp; import okhttp3.*; import java.io.IOException; public class OkHttpExample2 { // only one client private final OkHttpClient httpClient = new OkHttpClient(); public static void main(String[] args) throws IOException { OkHttpExample2 obj = new OkHttpExample2(); obj.sendGET(); } private void sendGET() throws IOException { Request request = new Request.Builder() .url("https://httpbin.org/get") .addHeader("custom-key", "mkyong") // add request headers .addHeader("User-Agent", "OkHttp Bot") .build(); httpClient.newCall(request).enqueue(new Callback() { @Override public void onFailure(Call call, IOException e) { e.printStackTrace(); } @Override public void onResponse(Call call, Response response) throws IOException { try (ResponseBody responseBody = response.body()) { if (!response.isSuccessful()) throw new IOException("Unexpected code " + response); // Get response headers Headers responseHeaders = response.headers(); for (int i = 0, size = responseHeaders.size(); i < size; i++) { System.out.println(responseHeaders.name(i) + ": " + responseHeaders.value(i)); } // Get response body System.out.println(responseBody.string()); } } }); } }
3. Параметры формы запроса на отправку
3.1 Добавить из параметров в Тело запроса
package com.mkyong.http; import okhttp3.*; import java.io.IOException; public class OkHttpExample3 { private final OkHttpClient httpClient = new OkHttpClient(); public static void main(String[] args) throws IOException { OkHttpExample3 obj = new OkHttpExample3(); obj.sendPOST(); } private void sendPOST() throws IOException { // form parameters RequestBody formBody = new FormBody.Builder() .add("username", "abc") .add("password", "123") .add("custom", "secret") .build(); Request request = new Request.Builder() .url("https://httpbin.org/post") .addHeader("User-Agent", "OkHttp Bot") .post(formBody) .build(); try (Response response = httpClient.newCall(request).execute()) { if (!response.isSuccessful()) throw new IOException("Unexpected code " + response); // Get response body System.out.println(response.body().string()); } } }
4. Запрос на публикацию – JSON
4.1 Создайте JSON Тело запроса
вручную.
package com.mkyong.http; import okhttp3.*; import java.io.IOException; public class OkHttpExample4 { private final OkHttpClient httpClient = new OkHttpClient(); public static void main(String[] args) throws IOException { OkHttpExample4 obj = new OkHttpExample4(); obj.sendPOST(); } private void sendPOST() throws IOException { // json formatted data String json = new StringBuilder() .append("{") .append("\"name\":\"mkyong\",") .append("\"notes\":\"hello\"") .append("}").toString(); // json request body RequestBody body = RequestBody.create( json, MediaType.parse("application/json; charset=utf-8") ); Request request = new Request.Builder() .url("https://httpbin.org/post") .addHeader("User-Agent", "OkHttp Bot") .post(body) .build(); try (Response response = httpClient.newCall(request).execute()) { if (!response.isSuccessful()) throw new IOException("Unexpected code " + response); // Get response body System.out.println(response.body().string()); } } }
5. Идентификация
Запустите простое веб-приложение Spring Security, обеспечивающее базовую аутентификацию HTTP, и протестируйте его с помощью библиотеки OkHttp.
5.1 Аутентификация заголовка по Запросу
напрямую.
Request request = new Request.Builder() .url("http://localhost:8080/books") .addHeader("Authorization", Credentials.basic("user", "password")) .build();
5.2 Создайте Аутентификатор
, более гибкий для обработки аутентификации.
private final Authenticator authenticator = new Authenticator() { @Override public Request authenticate(Route route, Response response) throws IOException { if (response.request().header("Authorization") != null) { return null; // Give up, we've already attempted to authenticate. } System.out.println("Authenticating for response: " + response); System.out.println("Challenges: " + response.challenges()); String credential = Credentials.basic("user", "password"); return response.request().newBuilder() .header("Authorization", credential) .build(); } }; private final OkHttpClient httpClient = new OkHttpClient .Builder() .authenticator(authenticator) .build();
6. Часто задаваемые вопросы
6.1 Отключено перенаправление.
private final OkHttpClient httpClient = new OkHttpClient.Builder() .followRedirects(false) .build();
6.2 Тайм-аут, 5 секунд.
private final OkHttpClient httpClient = new OkHttpClient.Builder() .connectTimeout(5, TimeUnit.SECONDS) .writeTimeout(5, TimeUnit.SECONDS) .readTimeout(5, TimeUnit.SECONDS) .build();
Рекомендации
Оригинал: “https://mkyong.com/java/okhttp-how-to-send-http-requests/”