The following code has been copied out for Horstmann's, Big Java Early Objects 6th edition - Chapter 23.3. The only modification is the package, added by eclipse.
The code:
package zipCodeScrapper;
import java.io.InputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.net.Socket;
import java.util.Scanner;
public class client {
public static void main(String[] args) throws IOException {
// Get command-line arguments
String host;
String resource;
if (args.length == 2) {
host = args[0];
resource = args[1];
} else {
System.out.println("Getting / from horstmann.com");
host = "horstmann.com";
resource = "/";
}
// Open socket
final int HTTP_PORT = 80;
try (Socket s = new Socket(host, HTTP_PORT)) {
// Get streams
InputStream instream = s.getInputStream();
OutputStream outstream = s.getOutputStream();
// Turn streams into scanners and writers
Scanner in = new Scanner(instream);
PrintWriter out = new PrintWriter(outstream);
// Send command
String command = "GET " + resource + " HTTP/1.1\n" + "Host: " + host + "\n\n";
out.print(command);
out.flush();
while (in.hasNextLine()) {
String input = in.nextLine();
System.out.println(input);
}
}
}
}
The code receives a 400 Bad Request. I have tried replacing the host and resources with other values, however I continue to get error 400.
Firstly , read this documentations. RFC p1 and RFC2 p2
Line separator of HTTP is not a \n
. It must be \r\n
. For more read this thread ;