Reputation: 1344
I'm submitting POST parameters in my Android app, however, none are received by the server (request().body().asFormUrlEncoded()
in Play Framework returns an empty Map). Here's the AsyncTask code used to submit the request:
private static AsyncTask<String, Void, String> register = new AsyncTask<String, Void, String>() {
@Override
protected String doInBackground(String... params) {
String email = params[0], username = params[1], password = params[2];
try {
URL url = new URL(REGISTER);
HttpURLConnection conn;
conn = (HttpURLConnection)url.openConnection();
conn.setDoOutput(true);
String urlParams = URLEncoder.encode("username=" + username + "&email=" + email + "&password=" + password, "UTF-8");
conn.setRequestMethod("POST");
conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
conn.setRequestProperty("Content-Length", String.valueOf(urlParams.length()));
conn.connect();
OutputStreamWriter writer = new OutputStreamWriter(conn.getOutputStream());
writer.write(urlParams);
writer.flush();
writer.close();
int resp = conn.getResponseCode();
Object content = conn.getContent();
conn.disconnect();
if(resp != 200)
return ERROR + "Bad response: " + resp + ", ";// + conn.getContent();
return content.toString();
} catch (IOException e) {
System.out.println("IOException occurred: ");
e.printStackTrace();
return ERROR + e.getMessage();
}
}
};
I do plan on making something prettier, but I need to make this work first. Every answer so far suggested something I've already done (e. g. connect()
, setting Content-Length
, closing the Writer after finished, getting the response) and it still doesn't work. Connection is received by the server, but the body is empty and server returns 400
.
Upvotes: 0
Views: 548
Reputation: 310884
You don't need to either set the content-length or call connect()
: these are both automatic. But you need to set the content type via the API, not via a request property. Otherwise it gets overwritten by the API's default, which is why not encoding fixed it.
Upvotes: 2