我试图以字节为单位读取网页,但它总是在我的 java 控制台上返回“错误请求错误 400”消息(我在控制台上显示内容)。我找不到纠正它的方法,可能是因为我阅读了字节码。这是我的代码和结果:
Socket s = new Socket(InetAddress.getByName(req.hostname), 80);
PrintWriter socketOut = new PrintWriter(s.getOutputStream());
socketOut.print("GET "+ req.url + "\n\n");
socketOut.flush();
BufferedReader in = new BufferedReader(new InputStreamReader(s.getInputStream()));
StringBuffer buffer = new StringBuffer();
int data = in.read();
while (data != -1) {
char theChar = (char) data;
buffer.append(theChar);
data = in.read();
}
in.close();
byte[] result = buffer.toString().getBytes();
out.write(result);
结果包含从 Bad request 消息开始的 html 标签,但我删除了它们,所以这是我的结果:
Thread with id 10 URL: http://www.facebook.com.tr/
Host: www.facebook.com.tr
HTTP/1.1 400 Bad Request
Content-Type: text/html
Date: Wed, 17 Oct 2012 10:18:06 GMT
Connection: close
Content-Length: 134
400 Bad Request
Method Not Implemented
Invalid method in request