Search code examples
javahttpserverjson-rpc

How to handle unmatched/unwanted or valid request on Java HTTP Server?


I have a Java HTTPServer application listening JSON-RPC format POST requests on localhost:9090 as follows;

 HttpServer server = HttpServer.create(new InetSocketAddress(9090), 0);
            System.out.println("> Server started at port number: "+ port);          
            server.createContext("/serverStatus", new RootHandler());
            server.createContext("/newTransaction", new EchoTransactionHandler());
            server.createContext("/", new EchoPostHandler());               
            server.setExecutor(null);
            server.start();

I am sending all requests via POST and JSON-RPC format.The EchoPostHandler class meets all post requests made. EchoPosthandler decides which function will work by looking at the request body.

server.createContext("/", new EchoPostHandler());

All of the post request's url is localhost:9090/.

There are only 2 GET requests. One of these shows the server status. and its url is localhost:9090/serverStatus

My problem is; When the user sends an unwanted request, give it an appropriate answer. for example, it can call localhost:9090/status instead of calling localhost:9090/serverStatus to learn the server status.

I would like to return a proper answer in this case.

How can I handle this task?


Solution

  • The URL of all unwanted or non-context-defined requests acts as a base URL. Therefore, I have added a number of controls in EchoPostHandler to solve my problem.