Java 读取网页时出现错误的请求错误

Java 读取网页时出现错误的请求错误,java,Java,我试图读取以字节为单位的网页,但它总是在我的java控制台上返回“Bad Request Error 400”消息(我正在控制台上显示内容)。我找不到纠正的方法,可能是因为我读取字节代码。以下是我的代码和结果: Socket s = new Socket(InetAddress.getByName(req.hostname), 80); PrintWriter socketOut = new PrintWriter(s.getOutputStream())

我试图读取以字节为单位的网页,但它总是在我的java控制台上返回“Bad Request Error 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);
结果包含从错误请求消息开始的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

我认为这是因为您的代码无法处理在初始握手中接收到的永久重定向:

$>> curl --head www.facebook.com.tr/
HTTP/1.1 301 Moved Permanently
Location: http://www.facebook.com/
Content-Type: text/html; charset=utf-8
X-FB-Debug: WOU3E4EGqo5Rxch8AnUzqcWg9CcM1p55pt1P9Wrm0QI=
Date: Wed, 17 Oct 2012 10:33:12 GMT
Connection: keep-alive
Content-Length: 0
同时检查你的问题,你收到的是400而不是404

试试这个:

BufferedReader reader = new BufferedReader(new InputStreamReader(new URL("http://www.facebook.com.tr").openStream()));

String line = reader.readLine();
while(line!=null) {
    System.out.println(line);
    line = reader.readLine();
}

当您向HTTP服务器发送了不正确或不适当的请求时,HTTP服务将发送错误代码400。你必须确定你的要求是否正确。我看到
www.facebook.com.tr
。检查一下
.tr

服务器不允许没有声明的HTTP请求。试着这样做:

socketOut.print("GET "+ req.url + " HTTP/1.1\n\n");

还要考虑到服务器正在保持连接的活动状态,因此在某个时刻,
data=in.read()
将锁定主线程。除非您终止连接或执行其他操作,否则您的循环将需要一段时间才能结束,直到连接超时。

网址不仅仅是一个文本文件,您正在尝试与web服务器通信,需要执行某些握手以获取所需信息。我将用一些代码更新我的答案,这些代码应该可以满足您的要求。