如何修复 java.io.IOException:无法通过代理建立隧道。代理返回“HTTP/1.1 400 Bad Request”?

问题描述 投票:0回答:2

当调用 HttpURLConnection.getOutputStream() 时,我得到这个 IOException:

无法通过代理建立隧道。代理返回“HTTP/1.1 400 错误请求”

代码片段:

public static void main(String[] args) throws MalformedURLException, IOException {
        HttpURLConnection conn = (HttpURLConnection) new URL("https://example.com")
                .openConnection(new Proxy(Proxy.Type.HTTP, new InetSocketAddress("88.198.50.103", 3128)));
        conn.setDoOutput(true);

        try (OutputStream os = conn.getOutputStream(); OutputStreamWriter osw = new OutputStreamWriter(os)) {
            osw.write("Hello");
            osw.flush();
        } catch (IOException e) {
            System.err.println("Caught exception while opening outputstream.");
            e.printStackTrace();
        }
        System.out.println("Response: " + conn.getResponseMessage());
    }

产生的输出:

Caught exception while opening outputstream.
java.io.IOException: Unable to tunnel through proxy. Proxy returns "HTTP/1.1 400 Bad Request"
    at sun.net.www.protocol.http.HttpURLConnection.doTunneling(Unknown Source)
    at sun.net.www.protocol.https.AbstractDelegateHttpsURLConnection.connect(Unknown Source)
    at sun.net.www.protocol.http.HttpURLConnection.getOutputStream0(Unknown Source)
    at sun.net.www.protocol.http.HttpURLConnection.getOutputStream(Unknown Source)
    at sun.net.www.protocol.https.HttpsURLConnectionImpl.getOutputStream(Unknown Source)
    at application.Main.main(Main.java:31)
Response: Bad Request

我尝试了在互联网上找到的随机免费代理,所有代理都有相同的输出。

这与我的电脑有关吗?或者我使用代理的代码是错误的?

java proxy httpurlconnection ioexception bad-request
2个回答
0
投票
SocketAddress addr = new InetSocketAddress("104.248.63.17",30588);
    Proxy proxy = new Proxy(Proxy.Type.SOCKS, addr);
    URL url = new URL("https://www.proxy-listen.de/Proxy/Proxyliste.html");
    URLConnection   conn = url.openConnection(proxy);
    //follow code reads html from url 
    BufferedReader in = new BufferedReader(new InputStreamReader(conn.getInputStream()));
    String inputLine;
    while ((inputLine = in.readLine()) != null)
        System.out.println(inputLine);
    in.close();

这段代码对我有用。我在 https://www.proxy-listen.de/Proxy/Proxyliste.html 上搜索了 socks5 代理,然后它可以与袜子类型一起正常工作。


0
投票

我遇到了同样的问题。我认为如果代理服务器代表高级协议(例如 HTTP 或 FTP)的代理,它将不起作用。尝试更改为 Proxy.Type.SOCKS。

我发现这可能是旧 JDK 版本(包括 1.4 或 1.6)中的错误,但我使用 JDK 8。

© www.soinside.com 2019 - 2024. All rights reserved.