如何使HttpURLConnection使用代理?

房间:

如果我这样做

conn = new URL(urlString).openConnection();
System.out.println("Proxy? " + conn.usingProxy());

它打印

Proxy? false

问题是,我在代理后面。JVM在Windows的哪里获取代理信息?我该如何设置?我所有其他应用似乎都对我的代理完全满意。

尼克DK:

从Java 1.5开始,您还可以将java.net.Proxy实例传递给该openConnection(proxy)方法:

//Proxy instance, proxy ip = 10.0.0.1 with port 8080
Proxy proxy = new Proxy(Proxy.Type.HTTP, new InetSocketAddress("10.0.0.1", 8080));
conn = new URL(urlString).openConnection(proxy);

如果您的代理要求验证,它将给您响应407。

在这种情况下,您将需要以下代码:

    Authenticator authenticator = new Authenticator() {

        public PasswordAuthentication getPasswordAuthentication() {
            return (new PasswordAuthentication("user",
                    "password".toCharArray()));
        }
    };
    Authenticator.setDefault(authenticator);

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章