2014-11-17 84 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"