Play Framework / Java : A good way to send x-www-form-urlencoded data back

I have a Play Framework application (2.2.1) which have to send x-www-form-urlencoded data back. My controller action recovers the data with request().body().asFormUrlEncoded() which return a Map<String, String[]>.

In my action, I have to send this data back with this kind of way : WS.url(url).setContentType("application/x-www-form-urlencoded").post(data) (Before, I process operations on the URL). The issue is that post() accepts String, File, and others, but not the Map returned by asFormUrlEncoded(). It's a little annoying.

I have to rebuild the data in this way :

final Map<String, String[]> body = request().body().asFormUrlEncoded();
StringBuffer postBodyProv = new StringBuffer("");
Set<String> keys = body.keySet();
String result = null;
try {
    for (String key : keys) {
        postBodyProv.append(URLEncoder.encode(key, "UTF-8") + "=");
        String value = body.get(key)[0];
        postBodyProv.append(URLEncoder.encode(value, "UTF-8"));
        postBodyProv.append("&");
    }
    result = postBodyProv.substring(0, postBodyProv.length() - 1); // To skip the last "&"
} catch (UnsupportedEncodingException e) {
    e.printStackTrace();
}

Is there other (simpler) ways to do ? The values of the Map returned by asFormUrlEncoded() are arrays of Strings, is there cases where the array have more than one element ? In this case, how are they separated ?

Upvotes: 3

Views: 2519

Answers (1)

Didac Montero
Didac Montero

Reputation: 2086

Why don't you try converting the Map to JsonNode (which is valid in the post() method). I would also use DynamicForm:

final DynamicForm f = form().bindFromRequest();
WS.url(url).setContentType("application/x-www-form-urlencoded").
    post(play.libs.Json.toJson(f.data()));

Upvotes: 2

Related Questions