ceran
ceran

Reputation: 1412

Restlet: getting parameter keys and values of a request

I have a Restlet Service that looks like this:

@POST
@Produces("application/json")
public String processImmediately(String JSON) {

    //...
}

The intention is to pass a JSON string via POST. The parameter I used (String JSON) indeed contains the whole URL parameters, e.g.

JSON=%7B%22MessageType%22%3A%22egeg%22%7D&SomeValue=XY

I wonder how I could parse this. On the Restlet website, I found the following:

http://wiki.restlet.org/docs_2.0/13-restlet/27-restlet/330-restlet/58-restlet.html

Form form = request.getResourceRef().getQueryAsForm();
for (Parameter parameter : form) {
System.out.print("parameter " + parameter.getName());
System.out.println("/" + parameter.getValue());

How can I use this in my service method? I am even not able to determine the correct types (e.g. request, form). Do I need the method parameter any longer or is this a replacement?

Thanks

Upvotes: 1

Views: 2425

Answers (1)

Perception
Perception

Reputation: 80593

Your endpoint is being passed the entire query string because you didn't specify which part of it you want to consume. To bind just the JSON query parameter to your method try something like this:

@POST
@Path("/")
@Consumes("application/x-www-url-formencoded")
@Produces("application/json")
public String processImmediately(@FormParam("JSON") String json) {
    System.out.printf("Incoming JSON, decoded: %s\n", json);
    // ....
}

* EDIT *

You choose your method argument binding based on the expected content type. So for example if your Content-Type is application/x-www-form-urlencoded (Form Data), then you would bind a @FormParam. Alternatively, for Content-Type application/json you can simply consume the request body as a String.

@POST
@Path("/")
@Consumes("application/json")
@Produces("application/json")
public String processImmediately(String json) {
    System.out.printf("Incoming JSON, decoded: %s\n", json);
    // ....
}

If you find that you have URL encoded data when using the second method, then your client is passing its data to the server incorrectly.

Upvotes: 2

Related Questions