HttpClient 设置代理

最近遇到一个需求,服务器是内网,但是要请求外网的一些接口,因此需要通过设置代理来实现访问外网。

在查阅了网上的一些资料后发现大部分用的 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发起请求了。

  • 0
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值