Search code examples
androidhttpurlconnectionandroid-networking

missing parameter when sending request to server with HttpURLConnection


I need to post schoolname=xyz&schoolid=1234 to server. I wrote the following Android client code:

String data = "schoolname=xyz&schoolid=1234";

//The url is correct
HttpURLConnection conn = (HttpURLConnection)url.openConnection();
conn.setRequestMethod("POST");
conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
conn.setRequestProperty("Accept-Encoding", "gzip");
conn.setDoInput(true);
conn.setDoOutput(true);
OutputStream os = new BufferedOutputStream(conn.getOutputStream());
os.write(data.toString().getBytes("UTF-8"));

//response complains that missing parameter 'schoolname'
int responseCode = conn.getResponseCode();
...

After I send my request with above code, server however constantly complains that schoolname parameter is missing. What do I miss or did wrong?


Solution

  • I figured out myself, the reason is that I forget to call flush() on output stream. After flush it, everything works fine.