最近遇到一个需求,服务器是内网,但是要请求外网的一些接口,因此需要通过设置代理来实现访问外网。
在查阅了网上的一些资料后发现大部分用的 HttpClient 都不是 org.apache.commons.httpclient.HttpClient,由于我们使用的是这个,因此在参考了一些资料后整理如下:
声明:本文为 org.apache.commons.httpclient.HttpClient 使用代理服务器发起外网请求
Talk is cheap. Show me the code.
final HttpClient httpClient = new HttpClient();
// 代理用户名密码
UsernamePasswordCredentials credentials = new UsernamePasswordCredentials("", "");
// 代理start
httpClient.getState().setProxyCredentials(AuthScope.ANY, credentials);
HostConfiguration hostConfiguration = new HostConfiguration();
hostConfiguration.setProxy("代理服务器IP地址", 代理服务器端口3128);
// 代理end
final PostMethod method = new PostMethod(urlHead + urlPath);
method.setRequestHeader("Content-type", "application/x-www-form-urlencoded; charset=UTF-8");
if(params != null){
for (Map.Entry<String, String> entry : params.entrySet()) {
method.setParameter(entry.getKey(), entry.getValue());
}
}
String response = "";
try{
int status = httpClient.executeMethod(hostConfiguration, method);
if(status >= 300 || status < 200){
throw new RuntimeException("invoke api failed, urlPath:" + urlPath
+ " status:" + status + " response:" + method.getResponseBodyAsString());
}
response = CommonUtil.parserResponse(method);
} catch (HttpException e) {
System.out.println(e.getMessage());
} catch (IOException e) {
System.out.println(e.getMessage());
}finally{
method.releaseConnection();
}
以上是通过 org.apache.commons.httpclient.HttpClient 来做网络请求,其中本帖子最核心的代码就是使用HostConfiguration设置代理。
1. 定义代理
// 代理用户名密码
UsernamePasswordCredentials credentials = new UsernamePasswordCredentials("", "");
// 代理start
httpClient.getState().setProxyCredentials(AuthScope.ANY, credentials);
HostConfiguration hostConfiguration = new HostConfiguration();
hostConfiguration.setProxy("代理服务器IP地址", 代理服务器端口3128);
// 代理end
2. 使用代理发起请求
httpClient.executeMethod(hostConfiguration, method);
至此就可以使用代理来为我们定义的method发起请求了。