1. Download our Official Android App: Forums for Android!

Apps HttpURLConnection with POST method

Discussion in 'Android Development' started by jesb, Aug 15, 2011.

  1. jesb

    jesb Lurker
    Thread Starter
    Rank:
    None
    Points:
    5
    Posts:
    5
    Joined:
    Jun 1, 2011

    Jun 1, 2011
    5
    0
    5
    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????:thinking:
     

    Advertisement

  2. jesb

    jesb Lurker
    Thread Starter
    Rank:
    None
    Points:
    5
    Posts:
    5
    Joined:
    Jun 1, 2011

    Jun 1, 2011
    5
    0
    5
  3. jonbonazza

    jonbonazza Android Expert
    Rank:
    None
    Points:
    163
    Posts:
    1,930
    Joined:
    Jul 13, 2010

    Jul 13, 2010
    1,930
    457
    163
    Male
    You are on the right track as to how to make it work, but here are some changes that might help:
    Code (Text):
    1.  
    2.  
    3. DefaultHttpClient client = new DefaultHttpClient();
    4. HttpPost req = new HttpPost([URL]https://mysite.com/Test.php[/URL]);
    5. List<NameValuePair> nvp = new List<NameValuePair>();
    6. nvp.add(new BasicNameValuePair("param1", "1"));
    7. nvp.add(new BasicNameValuePair("param2", "2"));
    8. req.setEntity(new UrlEncodedFormEntity(nvp));
    9.  
    10. String response = client.execute(req);
    11.  
     

Share This Page

Loading...