java网络请求的超时与重试解决方案

在Java中,处理网络请求时的超时和重试可以使用 HttpURLConnection 或更现代的库如 Apache HttpClient 或 OkHttp。以下是一些常见的解决方案。
使用 HttpURLConnection

java

import java.io.IOException;
import java.net.HttpURLConnection;
import java.net.URL;

public class HttpRequest {
    public static void main(String[] args) {
        String urlString = "https://example.com";
        int maxRetries = 3;

        for (int i = 0; i < maxRetries; i++) {
            try {
                HttpURLConnection connection = (HttpURLConnection) new URL(urlString).openConnection();
                connection.setConnectTimeout(5000); // 连接超时
                connection.setReadTimeout(5000);    // 读取超时
                connection.setRequestMethod("GET");

                int responseCode = connection.getResponseCode();
                if (responseCode == 200) {
                    System.out.println("请求成功!");
                    break; // 成功,退出重试
                }
            } catch (IOException e) {
                System.out.println("请求失败,重试 " + (i + 1) + "...");
            }
        }
    }
}

使用 Apache HttpClient

xml



    org.apache.httpcomponents
    httpclient
    4.5.13

java

import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;

public class HttpClientRequest {
    public static void main(String[] args) {
        String url = "https://example.com";
        int maxRetries = 3;

        try (CloseableHttpClient httpClient = HttpClients.createDefault()) {
            for (int i = 0; i < maxRetries; i++) {
                try {
                    HttpGet request = new HttpGet(url);
                    request.setConfig(RequestConfig.custom()
                        .setConnectTimeout(5000)
                        .setSocketTimeout(5000)
                        .build());

                    CloseableHttpResponse response = httpClient.execute(request);
                    if (response.getStatusLine().getStatusCode() == 200) {
                        String responseBody = EntityUtils.toString(response.getEntity());
                        System.out.println("请求成功:" + responseBody);
                        break;
                    }
                } catch (IOException e) {
                    System.out.println("请求失败,重试 " + (i + 1) + "...");
                }
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

使用 OkHttp

xml



    com.squareup.okhttp3
    okhttp
    4.9.2

java

import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;

import java.io.IOException;

public class OkHttpRequest {
    public static void main(String[] args) {
        OkHttpClient client = new OkHttpClient.Builder()
                .connectTimeout(5, TimeUnit.SECONDS)
                .readTimeout(5, TimeUnit.SECONDS)
                .build();

        String url = "https://example.com";
        int maxRetries = 3;

        for (int i = 0; i < maxRetries; i++) {
            try {
                Request request = new Request.Builder().url(url).build();
                Response response = client.newCall(request).execute();

                if (response.isSuccessful()) {
                    System.out.println("请求成功:" + response.body().string());
                    break; // 成功,退出重试
                }
            } catch (IOException e) {
                System.out.println("请求失败,重试 " + (i + 1) + "...");
            }
        }
    }
}

重点

    超时设置:通过设置连接超时和读取超时来确保请求不会无限等待。
    重试机制:在捕获异常时进行重试,通常建议设置最大重试次数。
    异常处理:确保适当处理可能的网络异常。

请使用浏览器的分享功能分享到微信等