开发者

Can I set the proxy on the command line when using org.apache.commons.httpclient?

开发者 https://www.devze.com 2023-01-27 15:06 出处:网络
If an application uses the java.net.* routines, I can set a proxy when invoking the application like this:

If an application uses the java.net.* routines, I can set a proxy when invoking the application like this:

java -Dhttp.proxyHost=proxy.server.com -Dhttp.proxyPort=8000 <whatever-the-app-is>

However, I have an application (which I can't change) using org.apache.commons.httpclient to do the http communication. It doesn't specify a procxy server, but it does use the default HttpConnection. Is there some way I can tell the apache htt开发者_C百科p client from the command line to use a proxy server?


When using the HTTPClient builder use the useSystemProperties() method to enable the standard JVM -D proxy parameters.
See http://hc.apache.org/httpcomponents-client-ga/httpclient/apidocs/org/apache/http/impl/client/HttpClientBuilder.html#useSystemProperties()

Example:

CloseableHttpClient httpclient = HttpClients.custom()
    .useSystemProperties()
    .build();

Now use -Dhttp.proxyHost=10.0.0.100 -Dhttp.proxyPort=8800 to configure the proxy.


Unfortunately, I don't think you can. The only way is for the application to read the System property and then set it in the DefaultHttpParams object.

Take a look at this thread on the httpclient-user group for more details.


I don't think so. But here is a code I found this code in an old project, which should've worked:

try {
   String proxyHost = System.getProperty("https.proxyHost");
   int proxyPort = 0;
   try {
        proxyPort = Integer.parseInt(System.getProperty("https.proxyPort"));
   } catch (Exception ex) {
        System.out.println("No proxy port found");
   }

   System.setProperty("java.net.useSystemProxies", "true");

   ProxySelector ps = ProxySelector.getDefault();
   List<Proxy> proxyList = ps.select(new URI(targetUrl));
   Proxy proxy = proxyList.get(0);
   if (proxy != null) {
         InetSocketAddress addr = ((InetSocketAddress) proxy.address());
         if (addr != null) {
             proxyHost = addr.getHostName();
             proxyPort = addr.getPort();
         }
   }

   boolean useProxy = proxyHost != null && proxyHost.length() > 0;

   if (useProxy) {
         httpClient.getHostConfiguration().setProxy(proxyHost, proxyPort);
   }

} catch (Exception ex) {
   ex.printStackTrace();
}
0

精彩评论

暂无评论...
验证码 换一张
取 消