IOException в HTTP Java: причины, обработка и примеры
IOException в HTTP Java: базовый подход и варианты
Основной подход к IOException в HTTP Java строится на предсказуемой обработке сетевых сбоев, явных таймаутах и повторных попытках только для идемпотентных запросов. Вместо перехвата всех исключений подряд код разделяет DNS-ошибки, таймауты, отказы соединения и SSL-сбои.
- Создание HttpClient с connectTimeout.
- Установка request timeout для каждого запроса.
- Классификация IOException по подтипам.
- Повтор с экспоненциальной задержкой для ConnectException и SocketTimeoutException.
- Немедленный выход для UnknownHostException и SSLHandshakeException.
- Закрытие ресурсов и восстановление флага прерывания.
import java.io.IOException;
import java.net.ConnectException;
import java.net.SocketTimeoutException;
import java.net.URI;
import java.net.UnknownHostException;
import java.net.http.HttpClient;
import java.net.http.HttpRequest;
import java.net.http.HttpResponse;
import java.time.Duration;
public class HttpRetryDemo {
private static final HttpClient CLIENT = HttpClient.newBuilder()
.connectTimeout(Duration.ofSeconds(3))
.build();
public static void main(String[] args) throws Exception {
String url = "https://httpbin.org/get";
HttpResponse<String> response = getWithRetry(url, 3);
System.out.println("Статус: " + response.statusCode());
System.out.println("Тело: " + response.body().substring(0, Math.min(80, response.body().length())));
}
static HttpResponse<String> getWithRetry(String url, int maxAttempts) throws IOException, InterruptedException {
IOException last = null;
for (int attempt = 1; attempt <= maxAttempts; attempt++) {
try {
HttpRequest request = HttpRequest.newBuilder()
.uri(URI.create(url))
.timeout(Duration.ofSeconds(5))
.header("Accept", "application/json")
.GET()
.build();
return CLIENT.send(request, HttpResponse.BodyHandlers.ofString());
} catch (UnknownHostException e) {
last = e;
System.out.println("DNS error, повтор невозможен");
break;
} catch (ConnectException | SocketTimeoutException e) {
last = e;
System.out.println("Попытка " + attempt + ": " + e.getClass().getSimpleName());
if (attempt == maxAttempts) break;
long delay = (long) (Math.pow(2, attempt) * 500 + Math.random() * 250);
Thread.sleep(delay);
} catch (IOException e) {
last = e;
System.out.println("IO error: " + e.getMessage());
if (attempt == maxAttempts) break;
Thread.sleep(1000L * attempt);
}
}
throw last;
}
}Java http exception (исключение http в java)
Попытка 1: ConnectException
Попытка 2: SocketTimeoutException
Статус: 200
Тело: { ... }Http java io ioexception (ioexception в http java)
Типичные проблемы. Повтор неидемпотентных POST может создать дубликаты. Слишком короткий timeout вызывает лишние IOException. Перехват Exception скрывает InterruptedException. Отсутствие close у InputStream приводит к утечке соединений.
Решение: идемпотентные ключи, разумные таймауты, отдельная обработка InterruptedException, try-with-resources.
Как обработать IOException в HttpURLConnection?
HttpURLConnection входит в стандартную библиотеку. Он требует ручного управления потоками и таймаутами. Для ошибочных HTTP-статусов используется getErrorStream.
import java.io.*;
import java.net.*;
public class HttpUrlConnectionDemo {
public static void main(String[] args) throws IOException {
URL url = new URL("https://httpbin.org/status/404");
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setConnectTimeout(3000);
conn.setReadTimeout(5000);
conn.setRequestMethod("GET");
int code = conn.getResponseCode();
InputStream stream = code >= 400 ? conn.getErrorStream() : conn.getInputStream();
try (BufferedReader reader = new BufferedReader(new InputStreamReader(stream))) {
String line;
while ((line = reader.readLine()) != null) {
System.out.println(line);
}
} catch (SocketTimeoutException e) {
System.out.println("Таймаут чтения: " + e.getMessage());
} catch (IOException e) {
System.out.println("Сетевая ошибка: " + e.getMessage());
} finally {
conn.disconnect();
}
}
}
Проблема: getInputStream выбрасывает IOException для кодов 4xx и 5xx. Решение: проверка getResponseCode и использование getErrorStream.
Как обработать IOException в java.net.http.HttpClient?
HttpClient из Java 11 поддерживает HTTP/2, асинхронные вызовы и явные таймауты. IOException выбрасывается методами send и sendAsync.
import java.io.IOException;
import java.net.URI;
import java.net.http.*;
import java.time.Duration;
public class HttpClientDemo {
public static void main(String[] args) {
HttpClient client = HttpClient.newBuilder()
.connectTimeout(Duration.ofSeconds(3))
.build();
HttpRequest request = HttpRequest.newBuilder()
.uri(URI.create("https://httpbin.org/delay/10"))
.timeout(Duration.ofSeconds(5))
.GET()
.build();
try {
HttpResponse<String> response = client.send(request, HttpResponse.BodyHandlers.ofString());
System.out.println(response.statusCode());
} catch (IOException e) {
System.out.println("IOException: " + e.getClass().getSimpleName());
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
System.out.println("Прервано");
}
}
}
Как обработать IOException в Apache HttpClient 5?
Apache HttpClient 5 имеет собственные стратегии повторов и настройки таймаутов.
import org.apache.hc.client5.http.classic.methods.HttpGet;
import org.apache.hc.client5.http.config.RequestConfig;
import org.apache.hc.client5.http.impl.classic.*;
import org.apache.hc.core5.http.io.entity.EntityUtils;
import org.apache.hc.core5.util.Timeout;
import java.io.IOException;
public class ApacheHttpDemo {
public static void main(String[] args) throws IOException {
RequestConfig config = RequestConfig.custom()
.setConnectTimeout(Timeout.ofSeconds(3))
.setResponseTimeout(Timeout.ofSeconds(5))
.build();
try (CloseableHttpClient client = HttpClients.custom().setDefaultRequestConfig(config).build();
CloseableHttpResponse response = client.execute(new HttpGet("https://httpbin.org/get"))) {
System.out.println(response.getCode());
System.out.println(EntityUtils.toString(response.getEntity()));
} catch (IOException e) {
System.out.println("Apache IOException: " + e.getMessage());
}
}
}
Как обработать IOException в OkHttp?
OkHttp использует IOException для сетевых сбоев. Interceptor позволяет централизовать повторы.
import okhttp3.*;
import java.io.IOException;
import java.util.concurrent.TimeUnit;
public class OkHttpDemo {
public static void main(String[] args) {
OkHttpClient client = new OkHttpClient.Builder()
.connectTimeout(3, TimeUnit.SECONDS)
.readTimeout(5, TimeUnit.SECONDS)
.build();
Request request = new Request.Builder()
.url("https://httpbin.org/get")
.build();
try (Response response = client.newCall(request).execute()) {
System.out.println(response.code());
System.out.println(response.body().string());
} catch (IOException e) {
System.out.println("OkHttp IOException: " + e.getMessage());
}
}
}
Как отличить HTTP-ошибку от IOException?
HTTP-ошибка это код ответа 4xx или 5xx. IOException это сбой транспорта: соединение, DNS, TLS, таймаут. Некоторые клиенты могут выбрасывать IOException при нарушении протокола.
if (response.statusCode() >= 400) {
System.out.println("HTTP error: " + response.statusCode());
} else {
System.out.println("HTTP success");
}
try {
// HTTP call
} catch (UnknownHostException e) {
System.out.println("DNS или URL");
} catch (ConnectException e) {
System.out.println("Соединение отклонено");
} catch (SocketTimeoutException e) {
System.out.println("Таймаут");
} catch (SSLHandshakeException e) {
System.out.println("TLS сбой");
} catch (IOException e) {
System.out.println("Другой сбой ввода-вывода");
}
Расширенные примеры обработки IOException в HTTP Java
Повтор с экспоненциальной задержкой и джиттером
Пример показывает разделение повторяемых и неповторяемых сбоев, а также учет кодов 5xx.
import java.io.IOException;
import java.net.ConnectException;
import java.net.SocketTimeoutException;
import java.net.URI;
import java.net.http.*;
import java.time.Duration;
import java.util.concurrent.ThreadLocalRandom;
public class BackoffRetry {
private static final HttpClient CLIENT = HttpClient.newBuilder()
.connectTimeout(Duration.ofSeconds(2))
.build();
public static void main(String[] args) throws Exception {
String body = fetch("https://httpbin.org/get", 5);
System.out.println(body.substring(0, 60));
}
static String fetch(String url, int maxAttempts) throws IOException, InterruptedException {
IOException last = null;
for (int i = 1; i <= maxAttempts; i++) {
try {
HttpRequest request = HttpRequest.newBuilder()
.uri(URI.create(url))
.timeout(Duration.ofSeconds(4))
.GET()
.build();
HttpResponse<String> response = CLIENT.send(request, HttpResponse.BodyHandlers.ofString());
if (response.statusCode() >= 500 && i < maxAttempts) {
System.out.println("Сервер вернул " + response.statusCode() + ", повтор");
sleep(i);
continue;
}
return response.body();
} catch (ConnectException | SocketTimeoutException e) {
last = e;
System.out.println("Сбой сети на попытке " + i + ": " + e.getClass().getSimpleName());
if (i == maxAttempts) break;
sleep(i);
} catch (IOException e) {
last = e;
System.out.println("IOException: " + e.getMessage());
if (i == maxAttempts) break;
sleep(i);
}
}
throw last;
}
static void sleep(int attempt) throws InterruptedException {
long base = (long) Math.pow(2, attempt) * 200;
long jitter = ThreadLocalRandom.current().nextLong(0, 150);
Thread.sleep(base + jitter);
}
}
Сбой сети на попытке 1: ConnectException
Сбой сети на попытке 2: SocketTimeoutException
{"args":{},"headers":{...}}
Обработка SSLHandshakeException с диагностикой
Пример демонстрирует перехват TLS-сбоя и отделение его от общих IOException.
import javax.net.ssl.*;
import java.io.IOException;
import java.net.URI;
import java.net.http.*;
import java.security.cert.X509Certificate;
import java.time.Duration;
public class SslDiagnostic {
public static void main(String[] args) throws Exception {
HttpClient client = HttpClient.newBuilder()
.connectTimeout(Duration.ofSeconds(3))
.sslContext(trustAllContext())
.build();
HttpRequest request = HttpRequest.newBuilder()
.uri(URI.create("https://self-signed.badssl.com/"))
.GET()
.build();
try {
HttpResponse<String> response = client.send(request, HttpResponse.BodyHandlers.ofString());
System.out.println(response.statusCode());
} catch (SSLHandshakeException e) {
System.out.println("SSLHandshakeException: " + e.getCause());
} catch (IOException e) {
System.out.println("IOException: " + e.getMessage());
}
}
static SSLContext trustAllContext() throws Exception {
TrustManager[] trustAll = new TrustManager[] {
new X509TrustManager() {
public void checkClientTrusted(X509Certificate[] chain, String authType) {}
public void checkServerTrusted(X509Certificate[] chain, String authType) {}
public X509Certificate[] getAcceptedIssuers() { return new X509Certificate[0]; }
}
};
SSLContext context = SSLContext.getInstance("TLS");
context.init(null, trustAll, new java.security.SecureRandom());
return context;
}
}
SSLHandshakeException: java.security.cert.CertificateException: No subject alternative DNS name matching self-signed.badssl.com found.
Доверие всем сертификатам применимо только для тестовых стендов. В рабочем коде используется корректный truststore.
Чтение error stream в HttpURLConnection
import java.io.*;
import java.net.*;
public class ErrorStreamDemo {
public static void main(String[] args) throws IOException {
HttpURLConnection conn = (HttpURLConnection) new URL("https://httpbin.org/status/500").openConnection();
conn.setConnectTimeout(3000);
conn.setReadTimeout(5000);
int code = conn.getResponseCode();
InputStream input = code >= 400 ? conn.getErrorStream() : conn.getInputStream();
if (input == null) {
System.out.println("Нет тела ответа, код: " + code);
} else {
try (BufferedReader br = new BufferedReader(new InputStreamReader(input))) {
String line;
while ((line = br.readLine()) != null) {
System.out.println(line);
}
}
}
conn.disconnect();
}
}
{
"message": "Internal Server Error"
}
Асинхронный HttpClient с exceptionally
import java.io.IOException;
import java.net.URI;
import java.net.http.*;
import java.time.Duration;
import java.util.concurrent.CompletableFuture;
public class AsyncHttp {
public static void main(String[] args) {
HttpClient client = HttpClient.newBuilder()
.connectTimeout(Duration.ofSeconds(2))
.build();
HttpRequest request = HttpRequest.newBuilder()
.uri(URI.create("https://httpbin.org/delay/2"))
.timeout(Duration.ofSeconds(1))
.GET()
.build();
CompletableFuture<HttpResponse<String>> future = client.sendAsync(request, HttpResponse.BodyHandlers.ofString());
future.thenApply(HttpResponse::statusCode)
.exceptionally(ex -> {
Throwable cause = ex.getCause();
if (cause instanceof IOException) {
System.out.println("Async IOException: " + cause.getClass().getSimpleName());
} else {
System.out.println("Другая ошибка: " + cause);
}
return -1;
})
.thenAccept(code -> System.out.println("Код: " + code));
}
}
Async IOException: HttpTimeoutException Код: -1
Apache HttpClient 5 с HttpRequestRetryStrategy
import org.apache.hc.client5.http.HttpRequestRetryStrategy;
import org.apache.hc.client5.http.classic.methods.HttpGet;
import org.apache.hc.client5.http.impl.classic.*;
import org.apache.hc.core5.http.*;
import org.apache.hc.core5.http.protocol.HttpContext;
import org.apache.hc.core5.util.TimeValue;
import java.io.IOException;
public class ApacheRetry {
public static void main(String[] args) throws IOException {
HttpRequestRetryStrategy retry = new HttpRequestRetryStrategy() {
public boolean retryRequest(HttpRequest request, IOException exception, int execCount, HttpContext context) {
return execCount <= 3 && (exception instanceof java.net.ConnectException || exception instanceof java.net.SocketTimeoutException);
}
public boolean retryRequest(HttpResponse response, int execCount, HttpContext context) {
return execCount <= 3 && response.getCode() >= 500;
}
public TimeValue getRetryInterval(HttpResponse response, int execCount, HttpContext context) {
return TimeValue.ofMilliseconds(500L * execCount);
}
};
try (CloseableHttpClient client = HttpClients.custom().setRetryStrategy(retry).build()) {
try (CloseableHttpResponse response = client.execute(new HttpGet("https://httpbin.org/status/503"))) {
System.out.println(response.getCode());
}
}
}
}
503
OkHttp Interceptor для повторов
import okhttp3.*;
import java.io.IOException;
public class OkRetryInterceptor {
public static void main(String[] args) throws IOException {
OkHttpClient client = new OkHttpClient.Builder()
.addInterceptor(new RetryInterceptor(3))
.build();
Request request = new Request.Builder().url("https://httpbin.org/status/503").build();
try (Response response = client.newCall(request).execute()) {
System.out.println(response.code());
}
}
static class RetryInterceptor implements Interceptor {
private final int maxAttempts;
RetryInterceptor(int maxAttempts) { this.maxAttempts = maxAttempts; }
public Response intercept(Chain chain) throws IOException {
IOException last = null;
for (int i = 1; i <= maxAttempts; i++) {
try {
Response response = chain.proceed(chain.request());
if (response.code() >= 500 && i < maxAttempts) {
response.close();
continue;
}
return response;
} catch (IOException e) {
last = e;
if (i == maxAttempts) throw e;
}
}
throw last;
}
}
}
503
Возобновление загрузки файла после IOException
import java.io.*;
import java.net.*;
import java.nio.file.*;
public class ResumeDownload {
public static void main(String[] args) throws IOException {
Path target = Paths.get("file.zip");
long existing = Files.exists(target) ? Files.size(target) : 0;
HttpURLConnection conn = (HttpURLConnection) new URL("https://example.com/file.zip").openConnection();
conn.setRequestProperty("Range", "bytes=" + existing + "-");
conn.setConnectTimeout(3000);
conn.setReadTimeout(10000);
int code = conn.getResponseCode();
if (code == 206) {
try (InputStream in = conn.getInputStream();
OutputStream out = Files.newOutputStream(target, StandardOpenOption.APPEND)) {
byte[] buffer = new byte[8192];
int read;
while ((read = in.read(buffer)) != -1) {
out.write(buffer, 0, read);
}
}
} else if (code == 200) {
try (InputStream in = conn.getInputStream()) {
Files.copy(in, target, StandardCopyOption.REPLACE_EXISTING);
}
} else {
throw new IOException("Сервер вернул " + code);
}
conn.disconnect();
}
}
Файл file.zip дополнен или перезаписан в зависимости от поддержки Range.
Диагностика UnknownHostException и ConnectException
import java.net.*;
import java.io.IOException;
public class DiagnoseNetwork {
public static void main(String[] args) {
try {
InetAddress address = InetAddress.getByName("nonexistent.example.invalid");
System.out.println(address.getHostAddress());
} catch (UnknownHostException e) {
System.out.println("UnknownHostException: DNS не разрешил имя или URL содержит опечатку");
}
try (Socket socket = new Socket()) {
socket.connect(new InetSocketAddress("localhost", 65535), 2000);
} catch (ConnectException e) {
System.out.println("ConnectException: порт закрыт или сервер не слушает");
} catch (SocketTimeoutException e) {
System.out.println("SocketTimeoutException: фильтр или сервер не отвечает");
} catch (IOException e) {
System.out.println("Другой IOException: " + e.getMessage());
}
}
}
UnknownHostException: DNS не разрешил имя или URL содержит опечатку ConnectException: порт закрыт или сервер не слушает