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.
Server response:
Getting url parameter and sending response.
- import java.io.BufferedReader;
- import java.io.IOException;
- import java.io.InputStreamReader;
- 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 Test {
- public static void main(String[] args) throws Exception {
- HttpServer server = HttpServer.create(new InetSocketAddress(8002), 0);
- server.createContext("/test", new MyHandler());
- server.setExecutor(null); // creates a default executor
- server.start();
- }
- static class MyHandler implements HttpHandler {
- public void handle(HttpExchange t) throws IOException {
- System.out.println("New request"+t.getRequestURI());
- BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
- String response = "<h2>This is the response</h2>"+br.readLine();
- t.sendResponseHeaders(200, response.length());
- OutputStream os = t.getResponseBody();
- os.write(response.getBytes());
- os.close();
- }
- }
- }
From the browser:
http://localhost:8002/test?sms=helloServer response:
<h2>This is the response</h2>hi
Comments
Post a Comment