Skip to content

Instantly share code, notes, and snippets.

@SubOptimal
Last active April 2, 2019 19:49
Show Gist options
  • Save SubOptimal/911c4c2af0a6f98441dac28eed468245 to your computer and use it in GitHub Desktop.
Save SubOptimal/911c4c2af0a6f98441dac28eed468245 to your computer and use it in GitHub Desktop.
HTTP 308 - permanent redirect and Java 11 client

A simple demo for the usage of Java 11 HttpClient.

server

Start the simple Python HTTP server.

$ ./dummy-http-server.py

It listen on http://localhost:8080 and respond to a GET with a permanent redirect HTTP 308 to http://example.com.

client

To compile and run the Java client you need Java >= 11

compile:

$ javac HttpClient11.java

execute:

$ java HttpClient11

response:

<!doctype html>
<html>
<head>
    <title>Example Domain</title>
...

curl

Using curl instead of the Java client.

$ curl -L http://localhost:8080

response is the same as above with the Java client

#!/usr/bin/env python
import sys
if sys.version_info.major == 2:
# Python 2.x
from BaseHTTPServer import BaseHTTPRequestHandler, HTTPServer
elif sys.version_info.major == 3:
# Python 3.x
from http.server import BaseHTTPRequestHandler,HTTPServer
else:
print('ERROR: don\'t know how to handle your python version\n' + sys.version)
sys.exit(1)
class Handler(BaseHTTPRequestHandler):
def do_GET(self):
self.send_response(308)
self.send_header('Location', 'http://example.com')
self.end_headers()
self.wfile.write("<html><body><h1>Hello Duke.</h1></body></html>")
def run(server=HTTPServer, handler=Handler, port=8080):
address = ('', port)
httpd = server(address, handler)
print('Starting server on: ' + str(port))
httpd.serve_forever()
if __name__ == "__main__":
run()
/**
demo of Java 11 HttpClient
*/
import java.net.URI;
import java.net.http.HttpClient;
import java.net.http.HttpClient.Redirect;
import java.net.http.HttpRequest;
import java.net.http.HttpResponse;
import java.net.http.HttpResponse.BodyHandlers;
class HttpClient11 {
public static void main(String[] args) throws Exception {
HttpClient client = HttpClient.newBuilder()
.followRedirects(Redirect.ALWAYS)
.build();
HttpRequest request = HttpRequest.newBuilder()
.uri(URI.create("http://localhost:8080"))
.build();
client.sendAsync(request, BodyHandlers.ofString())
.thenApply(HttpResponse::body)
.thenAccept(System.out::println)
.join();
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment