以下代码用于每五秒从网站获取响应,但根据数据包分析器(例如 wireshark),结果总是有问题。我猜可能 HTTP 响应是用 GZIP 压缩的,读取时可能有问题。当我执行代码时,我可以Finishied
在 Eclipse 中获得多个(这意味着读取响应已完成GET / 1.1
),但根据数据包分析器我只能发送几个。为什么?如果我注释代码Thread.sleep(1000*5);
,我会Finished
很快看到(太快,根据我的网络速度这是不正常的),但GET / 1.1
仍然很慢。代码有什么问题?
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();
}
}