Create dynamically contexts for com.sun.net.httpserver.HttpServer (Java)
Asked Answered
K

2

8

I need to handle HTTP requests using com.sun.net.httpserver.HttpServer which requests are triggered by the following URL schema:

http://somehost:9000/<var>/<service>

<var> is a parameter which is passed to the <service>

<service> is a predefined service that the server provides

The problem is that the context path is not known at compile time (because of the <var>) so I can not just call createContext(String path, HttpHandler handler). How can I bind this kind of 'dynamic' context to a specific HttpHandler instance?

Kopeisk answered 8/11, 2014 at 9:45 Comment(2)
handle "/" then adapt in the handler?Sinusoidal
I was looking for more... let say... streamlined solution but it seems this is my only option. @RC., can you add your comment as an answer so I can mark it as accepted, thanks.Kopeisk
S
12

You can handle "/" and adapt the handler, something like this:

createContext("/", new HttpHandler(){
    @Override
    void handle(final HttpExchange exchange) throws IOException {
         // use getRequestURI()
    }
});

see also HttpExchange#getRequestURI()

Sinusoidal answered 16/11, 2014 at 17:48 Comment(1)
Is there no other way of parsing the path parameters ?Crowd
L
11

I know this is a very old thread, but for anyone who finds it, I hope my answer will help.

I was recently creating a similar server where I needed a URL handler for the form /person/[id]/[location] where "id" and "location" were variable values. But I also needed a /person handler.

I'm sure there's documentation on this somewhere, but I discovered that creatContext will assign a handler to whatever it first recognizes.

What that means is that all I had to do was define a handler for "/person" and inside that handler, check for the [id] and [location] values. If there were those values, the handler would do something different, if not, it would just do the /person handler.

I hope this helps!

Latterll answered 25/10, 2018 at 13:45 Comment(2)
Can you provide a code example of how you checked for the id and location values?Greeneyed
That's a good question! I did this for a school project and don't think I have the code any more unfortunately. I probably used getRequestURI and I think I remember separating the string based on '/'s to see if there was an id or location. Sorry!Latterll

© 2022 - 2024 — McMap. All rights reserved.