Skip to content

Instantly share code, notes, and snippets.

@dhobbs
Created August 1, 2013 08:25
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save dhobbs/6129500 to your computer and use it in GitHub Desktop.
Save dhobbs/6129500 to your computer and use it in GitHub Desktop.
Java code to redirect all http requests to https, using simpleframework
private static void startHttpsRedirector() throws IOException {
org.simpleframework.http.core.Container container = new org.simpleframework.http.core.Container() {
@Override
public void handle(Request request, Response response) {
Path path = request.getPath();
Query query = request.getQuery();
String rawHost = request.getValue("host");
System.out.println("Raw host: " + rawHost);
System.out.println("Raw path: " + path);
System.out.println("Raw query: " + query);
String host = rawHost.replaceFirst("\\:.*", "");
response.setStatus(Status.MOVED_PERMANENTLY);
String redirectTo = "https://" + host + path + (query.values().size() > 0 ? "?" + query : "");
System.out.println("redirectTo = " + redirectTo);
response.setContentType("*/*; charset=\"UTF-8\"");
response.setValue("Location", redirectTo);
response.setContentLength(0);
try {
response.commit();
response.close();
} catch (IOException e) {
e.printStackTrace();
}
}
};
Server server = new ContainerServer(container);
Connection connection = new SocketConnection(server);
SocketAddress address = new InetSocketAddress(8088);
connection.connect(address);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment