如何在Java中设置HttpClient请求的代理主机

sqserrrh  于 2023-01-16  发布在  Java
关注(0)|答案(5)|浏览(225)

我想在发送HttpClient请求之前设置代理。因为我可以连接它,curl命令设置代理,但使用Java代码我无法做到这一点。
curl 命令:

**curl -I -x IP:80  URL**

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"));

在我的java文件中进行上述代码更改后,我会遇到以下错误:

java.net.ConnectException: Connection refused (Connection refused)

这表明我无法将该URL与我试图用于连接该URL的代理连接起来。

b1zrtrql

b1zrtrql1#

本教程中给出了一个完整的示例:How do I setting a proxy for 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();
        }
    }
}

为此,您需要添加一个jar文件http://repo1.maven.org/maven2/commons-httpclient/commons-httpclient/3.1/commons-httpclient-3.1.jar

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

资源链接:https://stackoverflow.com/a/4957144

对于其他版本,如4.3或4.3+,您可以通过以下SO回答:Apache HttpClient 4.1 - Proxy Authentication

sdnqo3pr

sdnqo3pr2#

我想这可能会有帮助:

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"));
z0qdvdin

z0qdvdin3#

添加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>

使用HttpClientBuilder并设置标志useSystemProperties

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

那你至少有两个选择
备选办法A:推翻论点,即

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

选项B:设置JVM(${JAVA_HOME}/lib/net.properties):

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

并运行应用程序

cuxqih21

cuxqih214#

系统属性通常必须预先设置,这意味着在jvm启动时使用-Dhttp.proxyHost=some.host.com-Dhttp.proxyPort=8080,不要忘记httpsProxyHost和...端口)
或者哪个也应该在静态{}块中工作。
我个人觉得Jersey客户机实现更容易使用,如果您可以选择切换的话。

yzckvree

yzckvree5#

Java 17的工作原理如下:

HttpClient.newBuilder().proxy(ProxySelector.of(InetSocketAddress.createUnresolved("proxy.host.de", 3126))).build();

(3126是我代码片段中的代理端口。)

相关问题