Without changing code, how to force httpClient to use proxy by environment variables or JVM arguments

陌路散爱 提交于 2019-11-30 11:21:24

问题


I found setting http.proxyHost and http.proxyPort is of no use to httpClient. How to force the httpClient to use proxy by environment variables or VM arguments or something like those without changing code?


回答1:


in https://issues.apache.org/jira/browse/HTTPCLIENT-1128

SystemDefaultHttpClient was added to ver. 4.2

see http://hc.apache.org/httpcomponents-client-ga/httpclient/apidocs/org/apache/http/impl/client/SystemDefaultHttpClient.html




回答2:


HTTP client (v 4.5.1 for my case) can use system proxy like this:

HttpClient httpClient = HttpClientBuilder.create().useSystemProperties().build();
//or 
HttpClient httpClient = HttpClients.createSystem();



回答3:


you can force proxy to HttpClient by yourself with client.getHostConfiguration().setProxy(host, port) method. I usually create wrapper class around HttpClient and when initializing this class I setup proxy from whatever source (env. variables ...).

I used java.net.ProxySelector.setDefault(new MyProxySelector()) in situation where you can't set proxy directly on HttpClient. You have to implement your own ProxySelector class and method select makes proxy selection based on requested URI. You can make url->proxy mapping to configure particular URI address to required proxy or return one proxy for all requested URI globally.

As I can see in HttpClient source code, there's no other way how to configure proxy only setProxy method. I'm using commons-httpclient-3.1.




回答4:


AFAIK, you can't manage this without code changes but you can get closer to native behaviour by using your own connection manager. See ProxySelector changes URL's scheme from https:// to socket://




回答5:


Does this help?

System.setProperty("https.proxyHost", proxy_host);
System.setProperty("http.proxyHost", proxy_host);
System.setProperty("https.proxyPort", proxy_port);
System.setProperty("http.proxyPort", proxy_port);

Or ofcourse you can pass the same properties via the commandline



来源:https://stackoverflow.com/questions/5165126/without-changing-code-how-to-force-httpclient-to-use-proxy-by-environment-varia

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!