public String postSSLUrlWithParamsString url Map params String encoding String keyStorePath String encode = CHARSET; if !StringUtilisEmptyencoding encode = encoding;
要在该方法中加入代理,你可以使用HttpHost类来定义代理服务器的主机名和端口号,并使用DefaultProxyRoutePlanner类来设置代理路由计划。以下是修改后的代码示例:
public String postSSLUrlWithParams(String url, Map<String, String> 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();
HttpPost httpost = new HttpPost(url);
// 设置代理
if (!StringUtil.isEmpty(proxyHost) && proxyPort > 0) {
HttpHost proxy = new HttpHost(proxyHost, proxyPort);
httpclient.getParams().setParameter(ConnRoutePNames.DEFAULT_PROXY, proxy);
}
// 添加参数
List<NameValuePair> nvps = new ArrayList<NameValuePair>();
if (params != null && !params.isEmpty()) {
for (Map.Entry<String, String> entry : params.entrySet()) {
nvps.add(new BasicNameValuePair(entry.getKey(), 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, 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);
}
}
}
你可以在调用该方法时,传递代理服务器的主机名和端口号作为参数,如下所示:
String proxyHost = "your_proxy_host";
int proxyPort = 8080;
String response = postSSLUrlWithParams(url, params, encoding, keyStorePath, proxyHost, proxyPort);
``
原文地址: https://www.cveoy.top/t/topic/iKpm 著作权归作者所有。请勿转载和采集!