您的位置:首页 > 编程语言 > Java开发

Java使用代理发送Post请求

2019-05-14 12:17 176 查看
/**
*@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;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: