I am writing a simple program to send a get request to a specific url "http://badunetworks.com/about/". The request works if I send it to "http://badunetworks.com" but I need to send it to the about page.
package badunetworks;
import java.io.*;
import java.net.*;
public class GetRequest {
public static void main(String[] args) throws Exception {
GetRequest getReq = new GetRequest();
//Runs SendReq passing in the url and port from the command line
getReq.SendReq("www.badunetworks.com/about/", 80);
}
public void SendReq(String url, int port) throws Exception {
//Instantiate a new socket
Socket s = new Socket("www.badunetworks.com/about/", port);
//Instantiates a new PrintWriter passing in the sockets output stream
PrintWriter wtr = new PrintWriter(s.getOutputStream());
//Prints the request string to the output stream
wtr.println("GET / HTTP/1.1");
wtr.println("Host: www.badunetworks.com");
wtr.println("");
wtr.flush();
//Creates a BufferedReader that contains the server response
BufferedReader bufRead = new BufferedReader(new InputStreamReader(s.getInputStream()));
String outStr;
//Prints each line of the response
while((outStr = bufRead.readLine()) != null){
System.out.println(outStr);
}
//Closes out buffer and writer
bufRead.close();
wtr.close();
}
}
if the about page link is about.html ,then you have change this line
wtr.println("GET / HTTP/1.1")
intowtr.println("GET /about.html HTTP/1.1").
in socket creation remove the /about
wtr.println("GET / HTTP/1.1");
--->this line call the home page of the host you specified.you need open Socket to url without path e.g.
and after send command GET /{path} HTTP/1.1 e.g.
... other header...
When you're doing such a low-level access to a webserver, you should understand the 7 OSI layers. Socket is on layer 5 and HTTP on layer 7. That's also the reason, why java.net.Socket only accepts host names or InetAddr and no URLs. To do it with sockets, you have to implement the HTTP protocol properly, that is
www.badunetworks.com
and80
GET /about/ HTTP/1.1
But I wonder why you're doing it this complicated, there are a lot of alternatives to implementing low-level http clients yourself:
openStream()
to read it