为HttpClient设置静态代理

时间:2014-11-17 08:20:30

标签: java http proxy network-programming apache-httpclient-4.x

我想编写一个测试来测试我的服务,该服务使用HttpClient发送GET请求

    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));

当我在公司的网络中运行它时,由于它使用代理,它不起作用。

我不想更改我现有的服务代码,所以我希望找到一种方法来更改外部的set proxy,我的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();
        }   

2 个答案:

答案 0 :(得分:0)

您可以使用命令行

执行此操作

https://docs.oracle.com/javase/6/docs/technotes/guides/net/proxies.html

java -Dhttp.proxyHost=webcache.example.com -Dhttp.proxyPort=8080

答案 1 :(得分: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"
相关问题