如何在Java中使用代理获取URL连接?

14

我正在尝试在运行时使用代理创建URL连接。 我的代码如下:

Proxy proxy = new Proxy(Proxy.Type.HTTP, new InetSocketAddress("192.0.2.100", 80));
HttpURLConnection connection =
    (HttpURLConnection)new URL("http://abc.example.com").openConnection(proxy);

但这并没有起作用。有人知道原因吗?


4
有什么问题?你是否收到了堆栈跟踪或错误信息? - Udo Held
2
为什么它不工作?出了什么错误? - oers
你使用的是哪种类型的代理? - Emmanuel Bourg
谢谢大家,它起作用了。我需要配置连接请求。connection.setDoOutput(true); connection.setRequestProperty("Content-type", "text/xml"); connection.setRequestProperty("Accept", "text/xml, application/xml"); connection.setRequestMethod("POST"); - dku.rajkumar
你可以并且应该将你的解决方案作为这个问题的答案发布(之后你可以接受它)。 - oers
2个回答

18

为了帮助未来的访问者添加答案

Proxy proxy = new Proxy(Proxy.Type.HTTP, new InetSocketAddress("192.0.2.100", 80));
HttpURLConnection connection =(HttpURLConnection)new URL("http://abc.example.com").openConnection(proxy);
connection.setDoOutput(true);
connection.setDoInput(true);
connection.setRequestProperty("Content-type", "text/xml");
connection.setRequestProperty("Accept", "text/xml, application/xml");
connection.setRequestMethod("POST");

1
谢谢@dku.rajkumar,我该如何在这里设置用户名和密码? - Amol Bais

3
< p > dku.rajkumar 的方法对我无效。

我尝试了这个方法,它可以实现。但是需要两倍的时间。

Proxy proxy = new Proxy(Proxy.Type.HTTP, new InetSocketAddress("192.0.2.100", 80));

    HttpURLConnection connection =
        (HttpURLConnection)new URL("http://abc.example.com").openConnection(proxy);
    ((HttpURLConnection)new URL("http://abc.example.com").openConnection(proxy)).getInputStream();

System.out.println(connection.usingProxy());

结果为真

没有 ((HttpURLConnection)new URL("http://abc.example.com").openConnection(proxy)).getInputStream();

结果为假


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接