java网络编程,使用Socket访问web服务器

public class Demo07 {

public static void main(String[] args) throws UnknownHostException, IOException {
// TODO Auto-generated method stub
Socket socket = new Socket("www.bwchinese.com",80);
OutputStream os = socket.getOutputStream();
String get = "GET /article/1068213_2.html HTTP/1.1\r\nHost: www.bwchinese.com:80\r\nConnection: keep-alive\r\nAccept: text/html\r\nUser-Agent: Mozilla/5.0 (Windows NT 6.3; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/31.0.1650.63 Safari/537.36\r\nAccept-Encoding: gzip,deflate,sdch\r\nAccept-Language: zh-CN,zh;q=0.8\r\n\r\n";
os.write(get.getBytes());
InputStream is = socket.getInputStream();
BufferedReader bufr = new BufferedReader(new InputStreamReader(is));
String temp = null;
while((temp=bufr.readLine())!=null){
if(temp.length()==0)
break;
System.out.println(temp);
}
FileOutputStream fos = new FileOutputStream("F:\\t.txt");
BufferedWriter bufw = new BufferedWriter(new OutputStreamWriter(fos));
while((temp=bufr.readLine())!=null){ //最后程序就停留在这行,并且抛出java.net.SocketException:
//Connection reset异常
bufw.write(temp+"\n");
}
bufr.close();
bufw.close();
socket.close();
}

}

该程序不能读取完“http响应的content-length个字节”。且最终程序停留在最后一个readLine方法处。并且停留一段时间后,抛出异常java.net.SocketException: Connection reset。
请问这程序哪里错了,正确的写法是怎样的

temp.length == 0 的时候退出。
下边使用 temp 的时候 ,temp 不是 null 但是每次都能读取到一个 0长度的返回。所以会死循环,知道服务器断开。
可以边读取socket返回就别写入文件了呀。你这样读逻辑不对。
温馨提示:答案为网友推荐,仅供参考
相似回答
大家正在搜