0
votes

Here is my java http server program:

package alan;

import java.io.BufferedReader; 
import java.io.IOException; 
import java.io.InputStreamReader; 
import java.net.ServerSocket; 
import java.net.Socket; 

public class SimpleHTTPServer { 
    public static void main(String args[] ) throws IOException { 
        ServerSocket server = new ServerSocket(8080); 
        System.out.println("Listening for connection on port 8080 ...."); 
        while (true) { 
            Socket clientSocket = server.accept(); 
            InputStreamReader isr = new          InputStreamReader(clientSocket.getInputStream()); 
        BufferedReader reader = new BufferedReader(isr); 
        String line = reader.readLine(); 
        while (!line.isEmpty()) { 
            System.out.println(line); 
            line = reader.readLine(); 
        } 
    } 
} 
}

While this program is running, if i write "http://localhost:8080" on the web browser, the program can handle the Http get request and it prints the result on the Eclipse console but I want to do it by using java code.

Actually, first of all, i want to create a class which name is SimpleHTTPClient and i want to create a TCP Socket connection with SimpleHTTPServer class and send HTTPGET request via java code to my localhost. How can i do that? Actually, i can send HTTPGET request with URL connection like this:

package alan;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.Socket;
import java.net.URL;
import java.net.URLConnection;
import java.net.UnknownHostException;

public class SimpleHTTPClient {
    static Socket socket = null;

    public static void main(String args[]) throws UnknownHostException,     IOException {
    URL oracle = new URL("http://localhost:8080");
    URLConnection yc = oracle.openConnection();
    BufferedReader in = new BufferedReader(new InputStreamReader(yc.getInputStream()));
    String inputLine;
    while ((inputLine = in.readLine()) != null) 
        System.out.println(inputLine);
    in.close();
}
}

But i want to send HTTPGET request via TCP socket connection to my localhost. How can i do that?

1

1 Answers

1
votes

To do that, you have to print header of request. For a basic HTTP request, just add http method and host in header.

See the code bellow

Socket s = new Socket(InetAddress.getByName("stackoverflow.com"), 80);
PrintWriter pw = new PrintWriter(s.getOutputStream());
pw.println("GET / HTTP/1.1");
pw.println("Host: stackoverflow.com");
pw.println("");
pw.flush();
BufferedReader br = new BufferedReader(new InputStreamReader(s.getInputStream()));
String t;
while ((t = br.readLine()) != null) {
    System.out.println(t);
}
br.close();

Good luck