HttpURLConnection 与 https InputStream 乱码

HttpURLConnection with https InputStream Garbled

我使用 HttpURLConnection 来抓取 https://translate.google.com/

        InetSocketAddress addr = new InetSocketAddress("127.0.0.1", 1082);
        Proxy proxy = new Proxy(Proxy.Type.HTTP, addr);
        url = new URL("https://translate.google.com/");
        HttpURLConnection conn = (HttpURLConnection) url.openConnection(proxy);
        conn.setRequestProperty("Accept-Encoding", "gzip, deflate, sdch");
        conn.setRequestProperty("Connection", "keep-alive");
        conn.setRequestProperty("User-Agent",
                "Mozilla/5.0 (Linux; Android 6.0; Nexus 5 Build/MRA58N) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/46.0.2490.76 Mobile Safari/537.36");
        conn.setRequestProperty("Accept", "*/*");

        Map<String, List<String>> reqHeaders = conn.getHeaderFields();
        List<String> reqTypes = reqHeaders.get("Content-Type");
        for (String ss : reqTypes) {
            System.out.println(ss);
        }

        InputStream in = conn.getInputStream();
        String s = IOUtils.toString(in, "UTF-8");
        System.out.println(s.substring(0, 100));

        Map<String, List<String>> resHeader = conn.getHeaderFields();
        List<String> resTypes = resHeader.get("Content-Type");
        for (String ss : resTypes) {
            System.out.println(ss);
        }

控制台是

但是当我将 url 更改为 http://translate.google.com/ 时。 效果不错。

我在抓取 https://translate.google.com/ 时知道实际上 HttpURLConnection 是 HttpsURLConnection。 我尝试使用 HttpsURLConnection,它仍然是乱码。

有什么建议吗?

conn.setRequestProperty("Accept-Encoding", "gzip, deflate, sdch");

响应被压缩,因为上面的行告诉服务器客户端能够理解 Accept-Encoding 中指定的编码。

尝试评论这一行或处理这种情况。

HTTPS 有更具体的实现,即 HttpsURLConnection,以防您对 https 特定功能感兴趣,例如:

import javax.net.ssl.HttpsURLConnection;

....

URL url = new URL("https://www.google.com/");
HttpsURLConnection conn = (HttpsURLConnection) url.openConnection();

我接受 Jerry Chin 的 answer.Solves 我的问题。 我的回答只是记录我是如何解决这个问题的。 如果这种方法 unreasonable.Let 我知道,我会删除这个答案。

conn.setRequestProperty("Accept-Encoding", "gzip, deflate, sdch");

然后我检查响应内容-Encoding.It 的 gzip。

所以我用GZIPInputStream来接收。

InputStream in = conn.getInputStream();
GZIPInputStream gzis=new GZIPInputStream(in);
InputStreamReader reader = new InputStreamReader(gzis);
BufferedReader br = new BufferedReader(reader);

输入流正常

顺便说一句,如果你不需要接受编码,你可以删除它。

并且不要忘记检查用户代理。很重要,不同的操作系统对应不同的user-agent。