Search code examples
phpandroidhttp-postpost-parameter

How to extract POST parameters in php


From android app, I am calling my php script.

HttpPost httppost = new HttpPost("http://www.smth.net/some.php");
try {
// Add your data
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(2);
nameValuePairs.add(new BasicNameValuePair("pa", "555"));
nameValuePairs.add(new BasicNameValuePair("pb", "550"));
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));

// Execute HTTP Post Request
HttpResponse response = httpclient.execute(httppost);
}

How do I get the value of "pa" and "pb" in my php script.

I did $_POST['pa'] and urldecode($_POST['pa']) but both of these give me empty string.


Solution

  • You can use print_r($_POST) to debug what is being sent.

    If it helps, this is how I send info from Android using POST:

    JSONObject requestBody = new JSONObject();
    requestBody.put("pa", "550");
    requestBody.put("pb", "550");
    
    HttpPost requestBase = new HttpPost("url");
    StringEntity stringEntity = new StringEntity(requestBody.toString());
    stringEntity.setContentType(new BasicHeader(HTTP.CONTENT_TYPE, "application/json"));
    requestBase.setEntity(stringEntity);
    
    HttpResponse response = httpclient.execute(requestBase);
    

    I'm working from memory here though - there are a couple of try/catches you'll need to insert.

    Using a JSONObject might be unnecessary, but I found it gave me better flexibility and reliability.