我正在尝试在运行时使用代理创建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);
但这不起作用。有谁知道为什么?
答案 0 :(得分:13)
为未来访问者的帮助添加答案
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 :(得分:3)
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();
结果为假