2014-11-17 82 views
0

我想編寫一個測試來測試我的服務,使用HttpClient發送GET請求設置靜態代理HttpClient的

service.logger.info("Testing GET request with param= " + "test"); 
    service.logger.info(service.getSuggestions(searchTerms1)); 
    service.logger.info("Testing GET request with param= " + "weibo"); 
    service.logger.info(service.getSuggestions(searchTerms2)); 

當我運行這在我公司的網絡,這是行不通的,因爲它使用代理。

我不想更改我的服務的現有代碼,所以我希望找到一種方法來更改外部代理設置,並且我的HTTP客戶端將使用此代理髮送請求。有沒有辦法做到這一點?我正在使用eclipse。

以下是我如何發送請求從網絡獲取結果。

private final String getResultFromURL(String url) throws ClientProtocolException, IOException { 
      RequestConfig requestConfig = RequestConfig.custom().setConnectTimeout(1 * 1000).build(); 
      HttpClient client = HttpClientBuilder.create().setDefaultRequestConfig(requestConfig).build(); 
      HttpGet request = new HttpGet(url); 
      // add request header 
      request.addHeader("User-Agent", USER_AGENT_MOZILLIA); 

      HttpResponse response = client.execute(request); 

      StringBuffer result = new StringBuffer(); 
      try(BufferedReader rd = new BufferedReader(
             new InputStreamReader(response.getEntity().getContent()))){ 
       String line = ""; 
       while ((line = rd.readLine()) != null) { 
        result.append(line); 
       } 
      } 
      finally{ 
       request.releaseConnection(); 
       EntityUtils.consume(response.getEntity()); 
      } 

      logger.debug("----result from URL:"+url +" "+result); 
      return result.toString(); 
     } 

回答

0

您可以設置代理在JAVA_OPTIONS如下做到這一點。

在Windows

set _JAVA_OPTIONS=-Dhttp.proxyHost=proxyhostURL -Dhttp.proxyPort=proxyPortNumber -Dhttp.proxyUser=someUserName -Dhttp.proxyPassword=somePassword 

在* nix中

export _JAVA_OPTIONS="-Dhttp.proxyHost=proxyhostURL -Dhttp.proxyPort=proxyPortNumber -Dhttp.proxyUser=someUserName -Dhttp.proxyPassword=somePassword"