Skip to content

Instantly share code, notes, and snippets.

@tarrsalah
Created March 27, 2014 17:52
Show Gist options
  • Select an option

  • Save tarrsalah/9813806 to your computer and use it in GitHub Desktop.

Select an option

Save tarrsalah/9813806 to your computer and use it in GitHub Desktop.
simple Request/Response http scenario over TCP.
package org.tarrsalah.http_clients;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.MalformedURLException;
import java.net.Socket;
import java.net.URL;
import java.util.concurrent.CountDownLatch;
import java.util.logging.Level;
import java.util.logging.Logger;
/**
* SimpleHttpClient.java (UTF-8)
*
* Mar 27, 2014
*
* @author tarrsalah.org
*/
public class SimpleHttpClient {
private static final String CR = "\r\n";
private static final String CRCR = CR + CR;
public static void main(String[] args) {
if (args.length < 1) {
System.out.println("Usage : SimpleHttpClient <url>");
return;
}
try {
URL url = new URL(args[0]);
String host = url.getHost();
String path = url.getPath();
int port = url.getPort();
if (port < 80) {
port = 80;
}
//Construct and send the HTTP request
String request = new StringBuilder("GET ")
.append(path)
.append(" HTTP/1.1")
.append(CR)
.append("Connection: Close")
.append(CRCR)
.toString();
// Send the request over the socket
// Open a TCP connection
try (Socket socket = new Socket(host, port); // Send the request over the socket
PrintWriter writer = new PrintWriter(socket.getOutputStream());
BufferedReader reader = new BufferedReader(new InputStreamReader(socket.getInputStream()))) {
writer.print(request);
writer.flush();
// Read the response
reader.lines().forEach(System.out::println);
}
System.out.println("Finished");
} catch (MalformedURLException ex) {
Logger.getLogger(SimpleHttpClient.class.getName()).log(Level.SEVERE, null, ex);
} catch (IOException ex) {
Logger.getLogger(SimpleHttpClient.class.getName()).log(Level.SEVERE, null, ex);
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment