Compartilhamento de tecnologia

Como Java usa HttpClientUtils para iniciar solicitações HTTP

2024-07-12

한어Русский языкEnglishFrançaisIndonesianSanskrit日本語DeutschPortuguêsΕλληνικάespañolItalianoSuomalainenLatina


I. Introdução

No desenvolvimento de software moderno, muitas vezes é necessário comunicar-se com servidores remotos, como obter ou enviar dados. Apache HttpClient é uma biblioteca cliente Java HTTP popular que simplifica o processamento de inicialização e resposta de solicitações HTTP.Este artigo apresentará como usar um personalizadoHttpClientUtils Classe para usar Apache HttpClient para iniciar solicitações POST e gerenciar o pool de conexões para otimizar o desempenho.

1. Visão geral da classe HttpClientUtils

public class HttpClientUtils {
    // 静态常量和变量声明
    private static final int MAX_TOTAL_CONN = 600;
    private static final int MAX_CONN_PER_HOST = 300;
    private static final int SOCKET_TIMEOUT = 5000;
    private static final int CONNECTION_TIMEOUT = 200;
    private static final int CONNECTION_MANAGER_TIMEOUT = 100;

    private static CloseableHttpClient httpclient;
    private static PoolingHttpClientConnectionManager connMrg;
    private static String encoding = StandardCharsets.UTF_8.name();
    private static Logger log = LoggerFactory.getLogger(HttpClientUtils.class);
    private static final ScheduledExecutorService scheduledService = Executors.newScheduledThreadPool(2);

    // 静态代码块,用于初始化 HttpClient 和连接管理器,并设置 JVM 退出时关闭 HttpClient
    static {
        init();
        destroyByJvmExit();
    }

    // 初始化连接管理器和 HttpClient
    private static void init() {
        connMrg = new PoolingHttpClientConnectionManager();
        connMrg.setMaxTotal(MAX_TOTAL_CONN);
        connMrg.setDefaultMaxPerRoute(MAX_CONN_PER_HOST);

        httpclient = HttpClients.custom()
                .setConnectionManager(connMrg)
                .setDefaultRequestConfig(HttpClientUtils.defaultRequestConfig())
                .build();

        // 定时任务,定期清理过期和空闲连接
        scheduledService.scheduleAtFixedRate(() -> {
            connMrg.closeExpiredConnections();
            connMrg.closeIdleConnections(CONNECTION_MANAGER_TIMEOUT, TimeUnit.MILLISECONDS);
        }, 0, CONNECTION_MANAGER_TIMEOUT, TimeUnit.MILLISECONDS);
    }

    // JVM 退出时关闭 HttpClient
    private static void destroyByJvmExit() {
        Runtime.getRuntime().addShutdownHook(new Thread(() -> {
            try {
                httpclient.close();
            } catch (IOException e) {
                log.error("Error closing HttpClient: {}", e.getMessage());
            }
        }));
    }

    // 创建 HttpClientContext
    private static HttpClientContext createContext() {
        return HttpClientContext.create();
    }

    // 创建默认的 RequestConfig
    private static RequestConfig defaultRequestConfig() {
        return RequestConfig.custom()
                .setConnectTimeout(CONNECTION_TIMEOUT)
                .setSocketTimeout(SOCKET_TIMEOUT)
                .setConnectionRequestTimeout(CONNECTION_MANAGER_TIMEOUT)
                .build();
    }

    // 发起带参数的 POST 表单请求,返回字符串结果
    public static String postWithParamsForString(String url, List<NameValuePair> params) {
        HttpPost httpPost = new HttpPost();
        try {
            URI uri = new URIBuilder(url).build();
            httpPost.setURI(uri);
            httpPost.setEntity(new UrlEncodedFormEntity(params, StandardCharsets.UTF_8));

            return executeRequest(httpPost);
        } catch (URISyntaxException | IOException e) {
            log.error("Error executing POST request: {}", e.getMessage());
        } finally {
            httpPost.releaseConnection();
        }
        return null;
    }
    
    // 发起 GET 请求,返回字符串结果
    public static String get(String url, List<NameValuePair> params) {
        HttpGet httpGet = new HttpGet();
        try {
            URI uri = new URIBuilder(url).setParameters(params).build();
            httpGet.setURI(uri);

            return executeRequest(httpGet);
        } catch (URISyntaxException | IOException e) {
            log.error("HTTP GET request failed", e);
        } finally {
            httpGet.releaseConnection();
        }
        return null;
    }

    // 发起 Post 请求,返回字符串结果
    public static String post(String url, List<NameValuePair> params) {
        HttpPost httpPost = new HttpPost();
        try {
            httpPost.setURI(new URI(url));
            httpPost.setEntity(new UrlEncodedFormEntity(params, StandardCharsets.UTF_8));

            return executeRequest(httpPost);
        } catch (URISyntaxException | IOException e) {
            log.error("HTTP POST request failed", e);
        } finally {
            httpPost.releaseConnection();
        }
        return null;
    }

    // 执行 HTTP 请求并处理响应
    private static String executeRequest(HttpUriRequest request) throws IOException {
        try (CloseableHttpResponse response = httpclient.execute(request, createContext())) {
            int statusCode = response.getStatusLine().getStatusCode();
            if (statusCode == HttpStatus.SC_OK) {
                HttpEntity entity = response.getEntity();
                if (entity != null) {
                    return EntityUtils.toString(entity, encoding);
                } else {
                    log.warn("Empty response entity");
                }
            } else {
                log.error("HTTP request failed with status code: {}", statusCode);
            }
        } catch (IOException e) {
            log.error("HTTP request execution failed: {}", e.getMessage());
            throw e;
        }
        return null;
    }
}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  • 32
  • 33
  • 34
  • 35
  • 36
  • 37
  • 38
  • 39
  • 40
  • 41
  • 42
  • 43
  • 44
  • 45
  • 46
  • 47
  • 48
  • 49
  • 50
  • 51
  • 52
  • 53
  • 54
  • 55
  • 56
  • 57
  • 58
  • 59
  • 60
  • 61
  • 62
  • 63
  • 64
  • 65
  • 66
  • 67
  • 68
  • 69
  • 70
  • 71
  • 72
  • 73
  • 74
  • 75
  • 76
  • 77
  • 78
  • 79
  • 80
  • 81
  • 82
  • 83
  • 84
  • 85
  • 86
  • 87
  • 88
  • 89
  • 90
  • 91
  • 92
  • 93
  • 94
  • 95
  • 96
  • 97
  • 98
  • 99
  • 100
  • 101
  • 102
  • 103
  • 104
  • 105
  • 106
  • 107
  • 108
  • 109
  • 110
  • 111
  • 112
  • 113
  • 114
  • 115
  • 116
  • 117
  • 118
  • 119
  • 120
  • 121
  • 122
  • 123
  • 124
  • 125
  • 126
  • 127
  • 128
  • 129
  • 130
  • 131
  • 132
  • 133

2. Analise a classe HttpClientUtils

  1. constantes e variáveis ​​estáticas:

    • Define constantes e variáveis ​​como número máximo de conexões, tempo limite de conexão, tempo limite de soquete, etc.
  2. Inicialização e destruição:

    • Inicializado em bloco de código estático HttpClient e gerenciador de conexõesPoolingHttpClientConnectionManager
    • usar ScheduledExecutorService Limpe regularmente conexões expiradas e inativas.
    • existir destroyByJvmExit No método, um gancho de saída da JVM é registrado para garantir que ele seja fechado quando a JVM for encerrada.HttpClient
  3. Método de solicitação HTTP:

    • postWithParamsForString O método é usado para realizar uma solicitação POST com parâmetros.
    • usar HttpPost Crie a solicitação, defina o URL e os parâmetros da solicitação e, finalmente, chameexecuteRequest Solicitação de execução de método.
  4. Executar solicitações e processar respostas:

    • executeRequest Método receberHttpUriRequest, execute solicitações HTTP e processe respostas.
    • Verifique o código de status da resposta, e se for 200 (OK), leia a entidade de resposta e converta-a em uma string e retorne-a.
    • Use o log para registrar erros e mensagens de aviso para garantir a robustez e a confiabilidade do seu código.

3. Use a classe HttpClientUtils

usar HttpClientUtils As aulas podem simplificar a escrita e o gerenciamento de solicitações HTTP. As etapas específicas são as seguintes:

public class Main {
    public static void main(String[] args) {
        List<NameValuePair> params = new ArrayList<>();
        params.add(new BasicNameValuePair("param1", "value1"));
        params.add(new BasicNameValuePair("param2", "value2"));

        String response = HttpClientUtils.postWithParamsForString("http://example.com/api", params);
        if (response != null) {
            System.out.println("Response: " + response);
        } else {
            System.err.println("Failed to execute POST request");
        }
    }
}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14

Através do aprendizado acima, agora você deve entender como usar HttpClientUtils Classe para gerenciar clientes HTTP e iniciar solicitações. Essa abordagem pode ajudá-lo a lidar com a comunicação HTTP de maneira mais eficiente em aplicativos Java, ao mesmo tempo que melhora o desempenho e a estabilidade por meio de pooling de conexões e mecanismos de limpeza periódica.