简体   繁体   English

为HttpClient设置静态代理

[英]Set static proxy for HttpClient

I want to write a test to test my service which uses HttpClient to send GET request 我想编写一个测试来测试我的服务,该服务使用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));

When I am running this in my company's network, it does not work since it uses proxy. 当我在公司的网络中运行此程序时,由于使用了代理,因此它不起作用。

I don't want to change my existing code of my service, so I hope to find a way to change set proxy outside, and my HTTP client will send request using this proxy. 我不想更改服务的现有代码,因此希望找到一种在外部更改设置代理的方法,并且HTTP客户端将使用此代理发送请求。 Is there a way to do that? 有没有办法做到这一点? I am using eclipse. 我正在使用日食。

Below is how I send request to get result from network. 以下是我如何发送请求以从网络获取结果的方法。

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

You can do it with the commandline 您可以使用命令行来完成

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

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

You set the proxy in java_options as follows. 您可以在java_options中设置代理,如下所示。

In Windows 在Windows中

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

In *nix 在* nix中

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM