Question

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?

Was it helpful?

Solution 3

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

OTHER TIPS

Have a look at [this example that explains How to use a HttpURLConnection to POST data

If you're planning on doing a lot of web communication, take a look at Square's Retrofit which will help you automate a lot of this work.

You can't use the format "key=value&key1=value1" for http post. That would work fine only for get. In this case you need something like this:

List<NameValuePair> nameValuePairs;
nameValuePairs.add(new BasicNameValuePair("schoolname", "xyz"));
nameValuePairs.add(new BasicNameValuePair("schoolid", "1234"));
HttpPost httpPost = new HttpPost(url);
httpPost.setEntity(new UrlEncodedFormEntity(nameValuePairs, "UTF-8"));
httpPost.execute();
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top