Skip to content

Instantly share code, notes, and snippets.

@bneutra
Created October 25, 2018 16:20
Show Gist options
  • Save bneutra/4d1251eee7e06210e0c2f8309ad66bea to your computer and use it in GitHub Desktop.
Save bneutra/4d1251eee7e06210e0c2f8309ad66bea to your computer and use it in GitHub Desktop.
Simple http test client
import java.net.*;
import java.io.*;
/**
* Connect to a url and send a HTTP HEAD request.
*
* Will print response info to stdout
*
* Exceptions will be printed to stdout.
* Examples:
* DNS lookup failure:
* java -cp target/client-0.1.0.jar Client http://www.example.comz/ 80
* Server: www.example.comz
* java.net.UnknownHostException: www.example.comz
*
* TCP connection failure/timeout (after 60s)
* java.net.SocketException: Network is unreachable (connect failed)
*
*/
public class Client {
public static void main(String[] args) {
if (args.length < 1) return;
URL url;
int port = Integer.parseInt(args[1]);
try {
url = new URL(args[0]);
} catch (MalformedURLException ex) {
ex.printStackTrace();
return;
}
String hostname = url.getHost();
System.out.println("Server: " + hostname);
try (Socket socket = new Socket(hostname, port)) {
OutputStream output = socket.getOutputStream();
PrintWriter writer = new PrintWriter(output, true);
writer.println("HEAD " + url.getPath() + " HTTP/1.1");
writer.println("Host: " + hostname);
writer.println("User-Agent: Simple Http Client");
writer.println("Accept: text/html");
writer.println("Accept-Language: en-US");
writer.println("Connection: close");
writer.println();
InputStream input = socket.getInputStream();
BufferedReader reader = new BufferedReader(new InputStreamReader(input));
String line;
while ((line = reader.readLine()) != null) {
System.out.println(line);
}
} catch (Exception ex) {
System.out.println(ex);
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment