Search code examples
javaphpandroidhttp-post

Send Data Via Post Android to PHP


So, i'm trying to send message via Post in Android to PHP here is the Android Java Function:

 //enviando para o backend
private void SendtoPHP(String reg) throws IOException {


    HttpClient httpclient = new DefaultHttpClient();
    HttpPost httppost = new HttpPost("http://bubbledev.com.br/gcm/getdevice.php");

    try{
        List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(2);
        nameValuePairs.add(new BasicNameValuePair("regid", "" + reg ));
        httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
        HttpResponse response = httpclient.execute(httppost);


    }
    catch (ClientProtocolException e) {
        // TODO Auto-generated catch block
    } catch (IOException e) {
        // TODO Auto-generated catch block
    }

}

The PHP:

<?php       
include 'conecta.php';
$device_token  = urldecode($_POST['regid']);    
$sql = "INSERT INTO corposa.deviceandroid"
              . " (id,device_token)"
              . " VALUES (NULL,'$device_token')";
mysqli_query($con,$sql);    

?>

The PHP is Just fine, I already tested it with a another Post and worked, but when the Android function tries $device_token dont recive any value and the SQL save a "" with the id at the table


Solution

  • I use this code which is similar to yours, except the ResponseHandler. It works for me.

    HttpClient Client = new DefaultHttpClient();
    
    List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(2);
    nameValuePairs.add(new BasicNameValuePair("id", sID));
    nameValuePairs.add(new BasicNameValuePair("etc", sETC));
    
    try {           
    
        String SetServerString = "";
    
        HttpClient httpclient = new DefaultHttpClient();
        HttpPost httppost = new HttpPost("http://your-url.com/script.php");
        httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
        ResponseHandler<String> responseHandler = new BasicResponseHandler();
    
        SetServerString = httpclient.execute(httppost, responseHandler);                
    
    }  catch(Exception ex) {
        // failed
    }