用soket连csdn首页,返回的是乱码?
但是估计修改请求头导致csdn返回错误页面的时候,却不是乱码,是什么原因?
代码如下:
public class CSDNTest {
public static void main(String[] args) {
Socket socket = null;
BufferedReader br = null;
try {
socket = new Socket("www.csdn.net", 80);
StringBuffer sb = new StringBuffer("GET / HTTP/1.1\r\n");
sb.append("Host: www.csdn.net\r\n");
sb
.append("User-Agent: Mozilla/5.0 (Windows NT 6.2; WOW64; rv:29.0) Gecko/20100101 Firefox/29.0\r\n");
sb
.append("Accept: text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8\r\n");
sb
.append("Accept-Language: zh-cn,zh;q=0.8,en-us;q=0.5,en;q=0.3\r\n");
sb.append("Accept-Encoding: gzip, deflate\r\n");
sb.append("Connection: keep-alive\r\n");
sb.append("If-Modified-Since: Sun, 20 Jul 2014 14:40:02 GMT\r\n");
sb.append("Cache-Control: max-age=0\r\n\r\n");
socket.getOutputStream().write(sb.toString().getBytes());
br = new BufferedReader(new InputStreamReader(socket
.getInputStream(), "utf-8"));
String line = null;
while ((line = br.readLine()) != null) {
System.out.println(line);
}
} catch (UnknownHostException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
if (br != null) {
br.close();
}
} catch (IOException e) {
e.printStackTrace();
}
try {
if (socket != null) {
socket.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
------解决方案--------------------
对 他们都会自动解析header然后帮你预先处理好数据,所以一般还是用他们好,用socket学习一下http协议还行,真正用太麻烦