0

I'm following this sample code, and would like to know if it is possible to get the full http GET request inside the handler method? For example I have http://localhost:8000/test?param1=value1&param2=value2

I can't find any way to get these params of the request. here is this code:

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 Test {

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

    static class MyHandler implements HttpHandler {
        @Override
        public void handle(HttpExchange t) throws IOException {
            String response = "This is the response";
            t.sendResponseHeaders(200, response.length());
            OutputStream os = t.getResponseBody();
            os.write(response.getBytes());
            os.close();
        }
    }
}
Community
  • 1
  • 1
Upsilon42
  • 241
  • 2
  • 17

1 Answers1

3

You have that fantastic parameter HttpExchange in your handler callback, which has a method getRequestURI(), that returns a URI, which has methods to get

  • the host
  • the port
  • the query string, both encoded and decoded

Just please note that if your application is reverse proxied, all you have is what the proxy server used to make the request (likely the hostname, the port and the protocol will be different, but some translation can also be done to other parts of the request)

Raffaele
  • 20,627
  • 6
  • 47
  • 86