• After 15+ years, we've made a big change: Android Forums is now Early Bird Club. Learn more here.

Apps HttpURLConnection with POST method

jesb

Lurker
I'm very new to android programming. I'm more used to c# programming.

I'm having problem sending POST data to a PHP page using HttpURLConnection.

i know that POST data has to be encoded in ascii and sent to the server in bytes format. this is what i did, and i have been unsuccessful. I tried following several web instruction to no avail.
URL url;
HttpURLConnection conn;
loginurl=new URL("https://mysite.com/test.php");
conn=(HttpURLConnection)loginUrl.openConnection();
conn.setRequestMethod("POST");
String charset = "UTF-8";
String qry =URLEncoder.encode("param1=1&param2=2",charset);
conn.setRequestProperty("Accept-Charset", charset);
conn.setRequestProperty("Content-Type", "application/x-ww-form-urlencoded");
conn.setRequestProperty("Content-Length", ""+Integer.toString(qry.getBytes().length));
conn.setUseCaches(false);
conn.setDoInput(true);
conn.setDoOutput(true);

//sendrequest
DataOutputStream out= new DataOutputStream(conn.getOutputStream());
txtResponse.setText(out.toString());
out.writeBytes(qry);
out.flush();
out.close();

in my PHP code, all i'm doing is spitting out the value of param1 and param 2. they all turned out empty.

i tried modifying the parameter so that it will encode only the values, but not the key. however i still can't make it to work.

i tried out.write(qry.getBytes);
also tried out.write(("param1=1&param2=2").getBytes));
nothing works!

what am i doing wrong????:confused:
 
You are on the right track as to how to make it work, but here are some changes that might help:
Code:
DefaultHttpClient client = new DefaultHttpClient();
HttpPost req = new HttpPost([URL]https://mysite.com/Test.php[/URL]);
List<NameValuePair> nvp = new List<NameValuePair>();
nvp.add(new BasicNameValuePair("param1", "1"));
nvp.add(new BasicNameValuePair("param2", "2"));
req.setEntity(new UrlEncodedFormEntity(nvp));
 
String response = client.execute(req);
 
Back
Top Bottom