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

dku*_*mar 12 java connection url proxy

我试图在运行时使用代理创建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);
Run Code Online (Sandbox Code Playgroud)

但这不起作用.谁知道为什么?

dku*_*mar 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");
Run Code Online (Sandbox Code Playgroud)