Java HttpClient 使用代理发送 HTTPS 请求:优化代码并添加代理设置

本文将介绍如何在 Java 中使用 HttpClient 发送 HTTPS 请求,并通过添加代理设置来提高请求速度和稳定性。我们将提供一个优化后的代码示例,其中包含代理设置的实现和常见异常的处理。

优化后的代码:

public String postSSLUrlWithParams(String url, Map params, String encoding, String keyStorePath, String proxyHost, int proxyPort) {
    String encode = CHARSET;
    if (!StringUtil.isEmpty(encoding)) {
        encode = encoding;
    }
    if(StringUtil.isEmpty(keyStorePath)){
        keyStorePath=KEY_STORE_PATH;
    }
    log.info('httpClient invocation');
    DefaultHttpClient httpclient = new DefaultHttpClient();
    
    // 设置代理
    if (!StringUtil.isEmpty(proxyHost) && proxyPort > 0) {
        HttpHost proxy = new HttpHost(proxyHost, proxyPort);
        httpclient.getParams().setParameter(ConnRoutePNames.DEFAULT_PROXY, proxy);
    }
    
    HttpPost httpost = new HttpPost(url);
    // 添加参数
    List<NameValuePair> nvps = new ArrayList<NameValuePair>();
    if (params != null && params.keySet().size() > 0) {
        Iterator iterator = params.entrySet().iterator();
        while (iterator.hasNext()) {
            Map.Entry entry = (Map.Entry) iterator.next();
            nvps.add(new BasicNameValuePair((String) entry.getKey(),
                    (String) entry.getValue()));
        }
    }
    StringBuilder sb = new StringBuilder();
    BufferedReader br = null;
    try {
        httpclient.getParams().setParameter(CoreConnectionPNames.CONNECTION_TIMEOUT, CONNECTION_TIMEOUT);
        httpclient.getParams().setParameter(CoreConnectionPNames.SO_TIMEOUT, SO_TIMEOUT);
        httpclient.getConnectionManager().getSchemeRegistry().register(new Scheme('http', DEFAULT_HTTP_PORT, PlainSocketFactory.getSocketFactory()));
//        httpclient.getConnectionManager().getSchemeRegistry().register(new Scheme('https', DEFAULT_HTTPS_PORT,getSSLSocketFactory(keyStorePath)));
        httpclient.getConnectionManager().getSchemeRegistry().register(new Scheme('https', DEFAULT_HTTPS_PORT,getTrustSSLSocketFactory()));
        httpost.setEntity(new UrlEncodedFormEntity(nvps, encode));
        HttpResponse response = httpclient.execute(httpost);
        HttpEntity entity = response.getEntity();
        br = new BufferedReader(new InputStreamReader(
                entity.getContent(), encode));
        String s = null;
        while ((s = br.readLine()) != null) {
            sb.append(s);
        }
        return sb.toString();

    } catch (UnsupportedEncodingException e) {
        log.error('创建通信异常', e);
        throw new RuntimeException('创建通信异常',e);
    } catch (IOException e) {
        log.error('读取流文件异常 ', e);
        throw new RuntimeException('读取流文件异常 ',e);
    } catch (Exception e) {
        log.error('通讯未知系统异常 ', e);
        throw new RuntimeException('通讯未知系统异常 ',e);
    } finally {
        try {
            if (br != null) {
                br.close();
            }
            httpost.releaseConnection();
            httpclient.getConnectionManager().shutdown();
        } catch (Exception e) {
            LOGGER.error(e.getMessage(), e);
        }
    }
}

代码解释:

  1. 添加代理参数: 在方法签名中添加了两个参数 proxyHostproxyPort,用于指定代理服务器的主机地址和端口号。
  2. 设置代理: 在创建 DefaultHttpClient 对象后,使用 setProxy 方法设置代理服务器信息。
  3. 处理异常: 代码中包含了对 UnsupportedEncodingExceptionIOExceptionException 等常见异常的处理,以确保程序的稳定性。

使用示例:

String proxyHost = '127.0.0.1';
int proxyPort = 8080;
String url = 'https://www.example.com/api/data';
Map<String, String> params = new HashMap<>();
params.put('key', 'value');
String response = postSSLUrlWithParams(url, params, 'UTF-8', null, proxyHost, proxyPort);
System.out.println(response);

结论:

通过添加代理设置,可以有效提高 HttpClient 发送 HTTPS 请求的速度和稳定性。以上代码示例展示了如何使用代理服务器来发送 HTTPS 请求,以及如何处理常见的异常。希望本文对您有所帮助!

Java HttpClient 使用代理发送 HTTPS 请求:优化代码并添加代理设置

原文地址: https://www.cveoy.top/t/topic/qqEf 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录