如何在 Java 中的 HttpClient 请求上设置代理主机
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/44821561/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to set proxy host on HttpClient request in Java
提问by Developer
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 do that.
我想HttpClient
在 URL 上发送请求之前设置代理。因为我能够连接它 curl 命令设置代理但使用 Java 代码我无法做到这一点。
Curl command:
卷曲命令:
**curl -I -x IP:80 URL**
Code change done in java file:
在 java 文件中完成的代码更改:
HttpClient client = new HttpClient();
System.getProperties().put("http.proxyHost", "someProxyURL");
System.getProperties().put("http.proxyPort", "someProxyPort");
EntityEnclosingMethod method = new PostMethod(url);
method.setRequestEntity(new StringRequestEntity(requestXML, "text/xml", "utf-8"));
With above code changes in my java file I am getting below error :
在我的 java 文件中更改了上述代码后,出现以下错误:
java.net.ConnectException: Connection refused (Connection refused)
Which shows that I am not able to connect that URL with the proxy I am trying to use to connect the URL.
这表明我无法将该 URL 与我试图用来连接 URL 的代理连接。
采纳答案by DontPanic
I think this could be helpful:
我认为这可能会有所帮助:
HttpClient client = new HttpClient();
HostConfiguration config = client.getHostConfiguration();
config.setProxy("someProxyURL", "someProxyPort");
Credentials credentials = new UsernamePasswordCredentials("username", "password");
AuthScope authScope = new AuthScope("someProxyURL", "someProxyPort");
client.getState().setProxyCredentials(authScope, credentials);
EntityEnclosingMethod method = new PostMethod(url);
method.setRequestEntity(new StringRequestEntity(requestXML, "text/xml", "utf-8"));
回答by SkyWalker
A full example is given in this tutorial: How do I setting a proxy for HttpClient?
本教程提供了一个完整示例:如何为 HttpClient 设置代理?
package org.kodejava.example.commons.httpclient;
import org.apache.commons.httpclient.Credentials;
import org.apache.commons.httpclient.HostConfiguration;
import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.HttpMethod;
import org.apache.commons.httpclient.HttpStatus;
import org.apache.commons.httpclient.UsernamePasswordCredentials;
import org.apache.commons.httpclient.auth.AuthScope;
import org.apache.commons.httpclient.methods.GetMethod;
import java.io.IOException;
public class HttpGetProxy {
private static final String PROXY_HOST = "proxy.host.com";
private static final int PROXY_PORT = 8080;
public static void main(String[] args) {
HttpClient client = new HttpClient();
HttpMethod method = new GetMethod("https://kodejava.org");
HostConfiguration config = client.getHostConfiguration();
config.setProxy(PROXY_HOST, PROXY_PORT);
String username = "guest";
String password = "s3cr3t";
Credentials credentials = new UsernamePasswordCredentials(username, password);
AuthScope authScope = new AuthScope(PROXY_HOST, PROXY_PORT);
client.getState().setProxyCredentials(authScope, credentials);
try {
client.executeMethod(method);
if (method.getStatusCode() == HttpStatus.SC_OK) {
String response = method.getResponseBodyAsString();
System.out.println("Response = " + response);
}
} catch (IOException e) {
e.printStackTrace();
} finally {
method.releaseConnection();
}
}
}
For this, you need to add a jar file: http://repo1.maven.org/maven2/commons-httpclient/commons-httpclient/3.1/commons-httpclient-3.1.jar
为此,您需要添加一个 jar 文件:http: //repo1.maven.org/maven2/commons-httpclient/commons-httpclient/3.1/commons-httpclient-3.1.jar
Complete Example of a Apache HttpClient 4.1, setting proxy can be found below
Apache HttpClient 4.1 的完整示例,可以在下面找到设置代理
HttpHost proxy = new HttpHost("ip address",port number);
DefaultHttpClient httpclient = new DefaultHttpClient();
httpclient.getParams().setParameter(ConnRoutePNames.DEFAULT_PROXY,proxy);
HttpPost httpost = new HttpPost(url);
List<NameValuePair> nvps = new ArrayList<NameValuePair>();
nvps.add(new BasicNameValuePair("param name", param));
httpost.setEntity(new UrlEncodedFormEntity(nvps, HTTP.ISO_8859_1));
HttpResponse response = httpclient.execute(httpost);
HttpEntity entity = response.getEntity();
System.out.println("Request Handled?: " + response.getStatusLine());
InputStream in = entity.getContent();
httpclient.getConnectionManager().shutdown();
Resource Link:https://stackoverflow.com/a/4957144
资源链接:https : //stackoverflow.com/a/4957144
For other version like 4.3 or 4.3+, you can go through this SO answer: Apache HttpClient 4.1 - Proxy Authentication
对于 4.3 或 4.3+ 等其他版本,您可以通过这个 SO 答案:Apache HttpClient 4.1 - Proxy Authentication
回答by Frischling
System properties usually have to be set right upfront, which means either in the jvm startup with
-Dhttp.proxyHost=some.host.com
-Dhttp.proxyPort=8080
, not forgetting the httpsProxyHost and ...Port)
系统属性通常必须预先设置,这意味着要么在 jvm 启动时使用
-Dhttp.proxyHost=some.host.com
-Dhttp.proxyPort=8080
,不要忘记 httpsProxyHost 和 ...端口)
Or which should work, too, in a static {} block.
或者哪个也应该在静态 {} 块中工作。
I personally find the Jersey client implementation easier to work with, if you have the option to switch.
如果您可以选择切换,我个人认为 Jersey 客户端实现更容易使用。
回答by Evgeny Lebedev
Add maven dependency (4.2.X+):
添加 maven 依赖(4.2.X+):
<dependency>
<groupId>org.apache.httpcomponents</groupId>
<artifactId>httpclient</artifactId>
<version>4.5.3</version>
<exclusions>
<exclusion>
<artifactId>commons-logging</artifactId>
<groupId>commons-logging</groupId>
</exclusion>
</exclusions>
</dependency>
Use HttpClientBuilder
and set flag useSystemProperties
:
使用HttpClientBuilder
和设置标志useSystemProperties
:
HttpClient client = HttpClientBuilder.create().useSystemProperties().build();
then you have two options at least:
那么你至少有两个选择:
Option A: Override arguments, i.e.
选项 A:覆盖参数,即
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
):
选项 B:设置 JVM ( ${JAVA_HOME}/lib/net.properties
):
java.net.useSystemProxies=true
http.proxyHost=some-host
http.proxyPort=some-port
and run your application
并运行您的应用程序