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發起請求了。

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章