2016-12-27 89 views
0

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

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

控制台是

enter image description here

但是当我改变的URL http://translate.google.com/。 它运作良好。

我知道其实HttpURLConnection是HttpsURLConnection,当我爬行器https://translate.google.com/。 我尝试使用HttpsURLConnection,它仍然是乱码。

有什么建议吗?

回答

2

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

由于上面的这一行告诉服务器客户端能够理解在Accept-Encoding中指定的编码,所以响应被压缩。

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

有用于HTTPSHttpsURLConnection一个更具体的实施中,如果你有兴趣在特定的HTTPS功能,例如:

import javax.net.ssl.HttpsURLConnection; 

.... 

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

我会尝试upadte接受编码。 –

+0

@TomGrylls尝试*删除*它。目前你对服务器说谎,你可以处理gzip编码,当你不能。或者不是。 – EJP

+0

我尝试我的代码没有Accept-Encoding.It是返回正常值,虽然不正确value.And我会处理这个。谢谢! –

0

我接受杰里齐秦的answer.Solves我的问题。 我的答案只是记录我如何解决这个问题。 如果这种方法是不合理的。让我知道,我会删除这个答案。

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

然后我检查响应Content-Encoding.It是gzip。

所以我使用GZIPInputStream接收。

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

InputStream正常。

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

不要忘记检查用户代理。这对于不同的用户代理来说是非常重要和不同的操作系统。

相关问题