Java program to handle http request

Handle http request from web browser.  Creating own server like tomcat, No need to deploy the code .Program will run with out any server.
Getting url parameter and sending response.




  1. import java.io.BufferedReader;
  2. import java.io.IOException;
  3. import java.io.InputStreamReader;
  4. import java.io.OutputStream;
  5. import java.net.InetSocketAddress;

  6. import com.sun.net.httpserver.HttpExchange;
  7. import com.sun.net.httpserver.HttpHandler;
  8. import com.sun.net.httpserver.HttpServer;

  9. public class Test {

  10.     public static void main(String[] args) throws Exception {
  11.         HttpServer server = HttpServer.create(new InetSocketAddress(8002), 0);
  12.         server.createContext("/test", new MyHandler());
  13.         server.setExecutor(null); // creates a default executor
  14.         server.start();
  15.         
  16.     }

  17.     static class MyHandler implements HttpHandler {
  18.         public void handle(HttpExchange t) throws IOException {
  19.          System.out.println("New request"+t.getRequestURI());
  20.          BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
  21.         
  22.             String response = "<h2>This is the response</h2>"+br.readLine();
  23.             t.sendResponseHeaders(200, response.length());
  24.             OutputStream os = t.getResponseBody();
  25.             os.write(response.getBytes());
  26.             os.close();
  27.         }
  28.     }

  29. }

From the browser:

http://localhost:8002/test?sms=hello

Server response:
<h2>This is the response</h2>hi

Comments

Popular posts from this blog

Today Walkin 14th-Sept

Spring Elasticsearch Operations

Hibernate Search - Elasticsearch with JSON manipulation