前言: 当你处于公司内网无法对外网的接口访问,但是我们有一些第三方的接口处于外网,所以这个时候就需要配置代理服务器发出请求达到我们想要的目的。
通过代理服务器访问外网:
通过HttpClient官网提供的文档,发现HttpClient4.5的代理服务器做如下配置(附上HttpClient官网提供的文档的地址) --------官网地址
public static String postHttp(String url,String timestamp,String sign) {
String result = "";
CloseableHttpClient httpclient = null;
CloseableHttpResponse res = null;
try {
HttpClientContext context = HttpClientContext.create();
// 创建一个httpClient对象
httpclient = HttpClients.createDefault();
//登陆 从配置文件中读取url(也可以写成参数)
HttpPost httpPost = new HttpPost(url);
// 设置代理HttpHost
HttpHost proxy = new HttpHost("****", 8080, "http");
// 设置认证
CredentialsProvider credsProvider = new BasicCredentialsProvider();
// 添加代理用户认证-用户名和密码
credsProvider.setCredentials(new AuthScope(proxy), new UsernamePasswordCredentials("****","****"));
HttpClients.custom().setDefaultCredentialsProvider(credsProvider).build();
RequestConfig config = RequestConfig.custom().setProxy(proxy).build();
// 设置参数
List<NameValuePair> formparams = new ArrayList<NameValuePair>();
formparams.add(new BasicNameValuePair("timestamp", timestamp));
formparams.add(new BasicNameValuePair("sign", sign));
UrlEncodedFormEntity uefEntity = new UrlEncodedFormEntity(formparams, "UTF-8");
httpPost.setEntity(uefEntity);
httpPost.setConfig(config);
// 得到响应状态码
res = httpclient.execute(httpPost,context);
// 获取返回对象
HttpEntity entity = res.getEntity();
// 通过EntityUtils获取返回结果内容
result = EntityUtils.toString(entity);
} catch (Exception e) {
e.printStackTrace();
} finally {
// 最后一定要释放资源
if(httpclient!=null) {
try {
httpclient.close();
} catch (Exception e) {
e.printStackTrace();
}
}
}
return result;
}