如题目所言,我有一个需求,需要模拟浏览器向指定URL交互,但是在取出内容时出现了问题,大多数网页都能正常抓取,因为响应头中包含了Content-Length;当遇到响应头中没有Content-Length时,代码就跑不下去了。如果一直使用readLine()方法一直读下去,如何判断流已读取到最末尾并不发生阻塞?跪求大神指点。
public static void main(String[] args)throws Exception
{
//创建连接到www.baidu.com的套接字
Socket s = new Socket("www.baidu.com",80);
//从套接字中获得输出流并包装成自动刷新的打印流
PrintWriter out = new PrintWriter(s.getOutputStream(),true);
//向打印流中输出HTTP请求消息头
out.println("GET / HTTP/1.1");
out.println("Accept: */*");
out.println("Accept-Language: zh-cn");
out.println("Host: www.baidu.com");
out.println("Connection: keep-alive");
out.println();
//获取套接字的输入流并包装成 BufferedReader
BufferedReader bufr = new BufferedReader(new InputStreamReader(s.getInputStream(),"utf-8"));
//获取HTTP响应头并存入HashMap
HashMap<String, String> headers = new HashMap<String, String>();
String line = null;
while((line=bufr.readLine())!=null)
{
//当读取到空行表示响应消息头结束
if(line.equals(""))break;
//将 Connection:keep-alive 这样的消息头劈开
String[] temp = line.split(":");
//此if为了避开响应状态 HTTP/1.1 200 OK
if(temp.length==2)
headers.put(temp[0], temp[1]);
else
headers.put(line, null);
}
line = null;
//将存好的响应头输出
for(String k :headers.keySet()){
System.out.println(k + ": " + headers.get(k));
}
System.out.println("------------------------------------------");
//取出内容长度
int sum = Integer.parseInt(headers.get("Content-Length").trim());
char[] cbuf = new char[sum];
int t = bufr.read(cbuf);
System.out.println(new String(cbuf,0,t));
bufr.close();
s.close();
}