Created
March 27, 2014 17:52
-
-
Save tarrsalah/9813806 to your computer and use it in GitHub Desktop.
simple Request/Response http scenario over TCP.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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