I was trying to read a web page in bytes but it always returns "Bad Request Error 400" message on my java console ( I'm displaying the content on my console). I couldn't find the way to correct it maybe it is because of my reading bytes code.Here is my code and result:
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);
And the result contains html tags starts from Bad request message but I delete them so here is my result:
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
I'd imagine it's because your code can't handle the permanent redirect it receives in the initial handshake:
$>> 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
Also check your question, it's a 400 you received not a 404.
Try this:
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();
}
Error code 400 is sent HTTP service when you have sent the incorrect or inappropriate request to a HTTP server. You have to be sure that whether your request is right. I see www.facebook.com.tr
. Check on that .tr
.
The server is not tolerating an HTTP request with no HTTP-Version
declaration. Try it like this:
socketOut.print("GET "+ req.url + " HTTP/1.1\n\n");
Also take into account that the server is keeping the connection alive, so at some point the data = in.read()
will lock the main thread. Unless you kill the connection or do something else, your loop will take a while to end until the connection times out.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.