Reputation: 749
I'm working through building a server in Java, following along with Horstmann's Big Java. When I finished a program that "simply establishes a connection to the host, sends a GET
command to the host, and then receives input from the server until the server closes its connection," I decided to try it on my own website.
The code that it returned looked nothing like what the html on my site looks like. In fact, it looks like something that's completely and totally hijacked my site. Of course, the site itself still looks just like always...
I'm really not sure what I am seeing here. I've double checked that the code is correct. Is the issue on the Java side, or is something off on my side?
Here is the Java:
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 WebGet {
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 thelinell.com");
host = "thelinell.com";
resource = "/";
}
// Open Socket
final int HTTP_PORT = 80;
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();
// Read server response
while (in.hasNextLine()) {
String input = in.nextLine();
System.out.println(input);
}
// Close the socket
s.close();
}
}
Now, the code that is returning looks like a bunch of advertisements and is rather long. Here is a pastebin of what it's giving me, for brevity. I will add it here if requested.
Upvotes: 2
Views: 156
Reputation: 80623
You need a space in-between the resource URI and the HTTP version fragment:
String command = "GET " + resource + "HTTP/1.1\n" ...
Should be:
String command = "GET " + resource + " HTTP/1.1\n" ...
As it is now, your request looks like this:
GET /HTTP/1.1
Host: thelinell.com
Which though not valid for HTTP 1.1, is still being intercepted by your web hosting provider (probably as a Simple-Request), which then spits back that (heinous) collection of banner ads.
Upvotes: 3