How to set proxy host on HttpClient request in Java

前端 未结 4 1136
野趣味
野趣味 2021-01-12 13:13

I want to set proxy before sending HttpClient request on a URL. As I am able to connect it curl command setting up the proxy but with Java code I am not able to

4条回答
  •  礼貌的吻别
    2021-01-12 13:46

    Add maven dependency (4.2.X+):

    
        org.apache.httpcomponents
        httpclient
        4.5.3
        
            
                commons-logging
                commons-logging
            
        
    
    

    Use HttpClientBuilder and set flag useSystemProperties:

    HttpClient client = HttpClientBuilder.create().useSystemProperties().build();
    

    then you have two options at least:

    Option A: Override arguments, i.e.

    java -Djava.net.useSystemProxies=true 
         -Dhttp.proxyHost=PROXY_HOST
         -Dhttp.proxyPort=PROXY_PORT 
         -Dhttp.proxyUser=USERNAME
         -Dhttp.proxyPassword=PASSWORD
         -jar your-app.jar
    

    Option B: Set up JVM (${JAVA_HOME}/lib/net.properties):

    java.net.useSystemProxies=true
    http.proxyHost=some-host
    http.proxyPort=some-port
    

    and run your application

提交回复
热议问题