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?