/**
*@param URL 需要请求的地址
**/
private String requestHttpsPost() throws Exception {
String result;
HttpPost post = new HttpPost(URL);
CloseableHttpClient client = null;
CloseableHttpResponse response = null;
HttpEntity entity = null;
try {
post.setHeader("Accept", "application/json, text/javascript, */*; q=0.01");
post.setHeader("X-Requested-With", "XMLHttpRequest");
post.setHeader("Content-Type", "application/x-www-form-urlencoded; charset=UTF-8");
List<BasicNameValuePair> formparam = new ArrayList<>();
//表单请求参数
post.setEntity(new UrlEncodedFormEntity(formparam));
// 设置客户端超时时间
RequestConfig config = RequestConfig.custom()
.setSocketTimeout(50000).setConnectTimeout(50000)
.setConnectionRequestTimeout(50000).build();
HttpClientBuilder httpClientBuilder = HttpClients.custom()
.setDefaultRequestConfig(config);
/***
*ForeignProxyHelp为自行封装的一个代理类
*/
ChannelProxy channelProxy = foreignProxyHelp.getProxy();
if (channelProxy != null) {
logger.info(channelProxy.getStunnelHost() + "---------------");
//取代理服务器的ip和端口
HttpHost targetHost = new HttpHost(
channelProxy.getStunnelHost(),
Integer.valueOf(channelProxy.getStunnelPort()));
CredentialsProvider credsProvider = new BasicCredentialsProvider();
credsProvider.setCredentials(
new AuthScope(targetHost.getHostName(),
targetHost.getPort()),
new UsernamePasswordCredentials(channelProxy.getProxyAccounts(),
channelProxy.getPassword()));
httpClientBuilder.setDefaultCredentialsProvider(credsProvider);
httpClientBuilder.setProxy(targetHost);
}
logger.info("设置代理完成...");
client = httpClientBuilder.build();
logger.info("获取客户端请求...");
// 执行POST请求
response = client.execute(post);
entity = response.getEntity();
int statusCode = response.getStatusLine().getStatusCode();
logger.info("执行请求结束...响应状态码:" + statusCode);
result = EntityUtils.toString(entity, "UTF-8");
} catch (Exception e) {
if (post != null) {
post.abort();
}
throw e;
} finally {
EntityUtils.consume(entity);
// 关闭连接 释放资源
if (post != null) {
post.releaseConnection();
}
if (response != null) {
response.close();
}
if (client != null) {
client.close();
}
}
return result;
}
Java使用代理发送Post请求
最新推荐文章于 2023-10-27 10:00:20 发布
本文详细介绍了如何使用Java进行HTTPS的POST请求,包括设置请求头、使用代理、处理响应等关键步骤,提供了完整的代码示例。
4504

被折叠的 条评论
为什么被折叠?



