I need to receive same POST data from a socket communication.
This is the code that send the POST and receive the response, and seems to work correctly:
String data = "t=" + URLEncoder.encode("Title", "UTF-8") +
"&u=" + URLEncoder.encode("http://www.myurl.com", "UTF-8");
URL url = new URL("http://localhost:9000/adserver");
URLConnection conn = url.openConnection();
conn.setDoOutput(true);
OutputStreamWriter wr = new OutputStreamWriter(conn.getOutputStream());
wr.write(data);
wr.flush();
BufferedReader rd = new BufferedReader(new InputStreamReader(conn.getInputStream()));
String output = "Data received\r\n", line;
while ((line = rd.readLine()) != null) {
output += line;
}
wr.close();
rd.close();
return ok(output);
This is the code that receive the POST:
Form<AdRequest> form = form(AdRequest.class).bindFromRequest();
if(form.hasErrors()) {
return badRequest("error");
} else {
AdRequest adr = form.get();
return ok(adr.t + " - " + adr.u);
}
The AdRequest model is defined in this way:
public class AdRequest {
public String t;
public String u;
}
The form object receive the data because I can see them in debug, but the adr object returned by the get() method contains only null values:
adr = {
t: null,
u: null
}
Instead, if I use this code to read the data it works correctly:
Map<String, String[]> asFormUrlEncoded = request().body().asFormUrlEncoded();
return ok(asFormUrlEncoded.get("t")[0] + " - " + asFormUrlEncoded.get("u")[0]);
What I'm doing wrong? Is it a Play Framework bug?
Thanks.
The problem for me, it seems, was that Eclipse was interfering with the code generation and generally messing up the generated bytecode.
Turning off "Build Automatically" in Eclipse fixed the problem.
This Link helped: https://groups.google.com/forum/?fromgroups#!topic/play-framework/JYlkz_Nh31g