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

2022-09-04 01:51:25

我正在尝试在运行时使用代理创建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);

但这是行不通的。有人知道为什么吗?


答案 1

为未来访客添加答案

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

答案 2

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

结果为假