Skip to content

Instantly share code, notes, and snippets.

@divanvisagie
Created June 9, 2013 10:59
Show Gist options
  • Select an option

  • Save divanvisagie/5743151 to your computer and use it in GitHub Desktop.

Select an option

Save divanvisagie/5743151 to your computer and use it in GitHub Desktop.
This happened
/*
Written by: Divan Visagie
Created On: 2013/06/09
This is my first attempt at actually doing something proper in Java
using nothing but a text editor and command line ,
I did it to make it snow (I was never a fan of java in the past but now I'm really open to new things)
*/
import java.io.IOException;
import java.io.OutputStream;
import java.net.InetSocketAddress;
import com.sun.net.httpserver.HttpExchange;
import com.sun.net.httpserver.HttpHandler;
import com.sun.net.httpserver.HttpServer;
public class HTTPExample{
public static void main( String[] args ) throws Exception{
System.out.println("Starting server");
HttpServer server = HttpServer.create( new InetSocketAddress(8080), 0 );
server.createContext("/test" , new TestHandler()); //this seems to create some sort of url context, im going to make a default as well
server.createContext("/" , new DefaultHandler());
server.setExecutor(null); //default apparently
server.start(); //the server will start listening
}
/* The following two handlers handle respective url context paths */
static class DefaultHandler implements HttpHandler{ //handler for /
public void handle(HttpExchange t) throws IOException{
/* Lets show what we are doing */
System.out.printf( "handling %s \n", t.getRequestURI().toString() );
String response = "This is the index";
t.sendResponseHeaders( 200, response.length());
OutputStream os = t.getResponseBody();
os.write(response.getBytes());
os.close();
}
}
static class TestHandler implements HttpHandler{ //handler for /test
public void handle(HttpExchange t) throws IOException{
System.out.printf( "handling %s \n", t.getRequestURI().toString() );
/* Build a response string and send the headers */
String response = "This is a response";
t.sendResponseHeaders(200, response.length());
// create some sort of output stream and write the response to it
OutputStream os = t.getResponseBody();
os.write( response.getBytes() );
os.close();
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment