Created
September 9, 2015 13:21
-
-
Save glebmtb/a8ef067c139f465a22f1 to your computer and use it in GitHub Desktop.
Http Server
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
import com.sun.net.httpserver.HttpExchange; | |
import com.sun.net.httpserver.HttpHandler; | |
import com.sun.net.httpserver.HttpServer; | |
import sun.net.httpserver.HttpServerImpl; | |
import java.io.IOException; | |
import java.io.OutputStream; | |
import java.net.InetSocketAddress; | |
import java.util.HashMap; | |
import java.util.Map; | |
public class TestServer { | |
public static void main(String[] args) throws IOException { | |
HttpServer httpServer = HttpServerImpl.create(new InetSocketAddress(3000), 0); | |
httpServer.createContext("/test", new MyHandler()); | |
httpServer.setExecutor(null); // creates a default executor | |
httpServer.start(); | |
} | |
private static class MyHandler implements HttpHandler { | |
@Override | |
public void handle(HttpExchange httpExchange) throws IOException { | |
String response = "{test1:1, test2:2}"; | |
System.out.println("I got request"); | |
Map<String,String> parms = queryToMap(httpExchange.getRequestURI().getQuery()); | |
System.out.println(parms); | |
httpExchange.getResponseHeaders().set("Content-type", "application/json"); | |
httpExchange.sendResponseHeaders(200, response.length()); | |
OutputStream os = httpExchange.getResponseBody(); | |
os.write(response.getBytes()); | |
os.close(); | |
} | |
} | |
public static Map<String, String> queryToMap(String query){ | |
Map<String, String> result = new HashMap<String, String>(); | |
for (String param : query.split("&")) { | |
String pair[] = param.split("="); | |
if (pair.length>1) { | |
result.put(pair[0], pair[1]); | |
}else{ | |
result.put(pair[0], ""); | |
} | |
} | |
return result; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment