写贴代码吧:
Socket socket = new Socket();
InetSocketAddress inetSocketAddress = new InetSocketAddress("music.163.com", 80);
socket.connect(inetSocketAddress);
OutputStream outputStream = socket.getOutputStream();
BufferedWriter bufferedWriter = new BufferedWriter(new OutputStreamWriter(outputStream));
bufferedWriter.write("GET /artist?id=10000 HTTP/1.1\r\n");
bufferedWriter.write("Host: music.163.com\r\n");
bufferedWriter.write("User-Agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/58.0.3029.110 Safari/537.36\r\n");
bufferedWriter.write("Accept: text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8\r\n");
bufferedWriter.write("Accept-Language: zh-CN,zh;q=0.9,en;q=0.8,fr;q=0.7\r\n");
bufferedWriter.write("\r\n");
bufferedWriter.flush();
InputStream inputStream = socket.getInputStream();
byte[] bytes = new byte[1024];
ByteArrayOutputStream baos = new ByteArrayOutputStream(1024 * 1024 * 4);
int len;
while ((len = inputStream.read(bytes, 0, bytes.length)) > 0) {
baos.write(bytes, 0, len);
}
System.out.println(baos.toString(StandardCharsets.UTF_8.name()));
输出如下:
HTTP/1.1 200 OK
Server: nginx
Date: Tue, 26 Dec 2017 02:14:35 GMT
Content-Type: text/html;charset=utf8
Transfer-Encoding: chunked
Connection: keep-alive
Vary: Accept-Encoding
Cache-Control: no-store
Pragrma: no-cache
Expires: Thu, 01 Jan 1970 00:00:00 GMT
Cache-Control: no-cache
Content-Language: zh-CN
X-Via: MusicServer
X-From-Src: 218.17.158.4
a3e
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="baidu-site-verification" content="cNhJHKEzsD" />
<meta property="qc:admins" content="27354635321361636375" />
...
</head>
<body>
...
</body>
</html>
响应里面,响应头和响应体之间的 'a3e\n' 是什么鬼?是因为网易的服务器没严格按照 http 协议来吗?还是说有啥特殊含义呢?
这是一个专为移动设备优化的页面(即为了让你能够在 Google 搜索结果里秒开这个页面),如果你希望参与 V2EX 社区的讨论,你可以继续到 V2EX 上打开本讨论主题的完整版本。
V2EX 是创意工作者们的社区,是一个分享自己正在做的有趣事物、交流想法,可以遇见新朋友甚至新机会的地方。
V2EX is a community of developers, designers and creative people.