以下代码用于每五秒钟从网站获取响应,但根据数据包分析器(如wireshark)的结果,总会出现错误。我想也许HTTP响应是用GZIP压缩的,读取它时可能会出错。当我执行代码时,我可以在Eclipse中获得多个Finishied
(,这意味着读取响应已完成),但根据数据包分析器的不同,我只能发送几个GET/1.1
。为什么?如果我对代码Thread.sleep(1000*5);
发表评论,我会很快看到Finished
(太快了,这是根据我的网络速度异常),但GET/1.1
仍然非常慢。代码有什么问题?如何使用gzip压缩读取HTTP响应?
public class pediy {
public static void main(String[] args) throws IOException {
URL url = new URL("http://bbs.pediy.com");
String request = "GET/HTTP/1.1\r\nHost: bbs.pediy.com\r\nProxy-Connection: keep-alive\r\nAccept: text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8\r\nUser-Agent: Mozilla/5.0 (Windows NT 6.1) AppleWebKit/537.17 (KHTML, like Gecko) Chrome/24.0.1312.56 Safari/537.17 CoolNovo/2.0.6.12\r\nAccept-Encoding: gzip,deflate,sdch\r\nAccept-Language: en-US;q=0.6,en;q=0.4\r\nAccept-Charset: utf-8;q=0.7,*;q=0.3\r\n";
Socket socket = null;
PrintWriter os = null;
BufferedReader is = null;
InputStreamReader isr = null;
while(true) {
socket = new Socket(url.getHost(), 80);
os = new PrintWriter(socket.getOutputStream());
isr = new InputStreamReader(socket.getInputStream());
is=new BufferedReader(isr);
try {
while (true) {
os.println(request);
os.flush();
while(is.read() != -1);
System.out.println("Finished");
Thread.sleep(1000*5);
}
} catch (Exception e) {
System.out.println("Error" + e);
} finally {
CloseAll(socket, os, is, isr);
}
}
}
private static void CloseAll(Socket socket, PrintWriter os, BufferedReader is, InputStreamReader isr) throws IOException {
if(socket != null) socket.close();
if(os != null) os.close();
if(is != null) is.close();
if(isr != null) isr.close();
}
}
哦,对不起,我粘贴了错误的代码,我纠正了它。 :-) – Searene