1

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

6 Answers 6

3

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
}
Sign up to request clarification or add additional context in comments.

1 Comment

NameValuePair is now considered as deprecated by Android studio - here is a separate thread on SO: stackoverflow.com/questions/29220755/namevaluepair-deprecated
2

I'm sure there are better ways to do this, but this is how I usually handle post requests from Android:

<?php
{
    $input = json_encode(file_get_contents("php://input"));

    $deviceToken = $input->regId;
    mysqli_query($connection, "INSERT INTO corposa.deviceandroid (`id`, `device_token`) VALUES(NULL, '" . mysqli_real_escape_string($deviceToken) . "')";
}

Also, since you're using POST instead of GET, the data being passed to the server isn't url encoded, so urldecode isn't needed here.

Comments

0

Code seems ok, only "strange" thing is:

List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(2);

because you are adding only ONE BasicNameValuePair to the list. Maybe that is the problem...?

Comments

0

I use this code in my current project, hope it's works for you too

  Map<String, String> kvPairs = new HashMap<String, String>();
    kvPairs.put("regid", reg);
    HttpClient httpclient = this.getNewHttpClient();
    HttpPost httppost = new HttpPost("http://bubbledev.com.br/gcm/getdevice.php");
    if (kvPairs != null && kvPairs.isEmpty() == false) {
        List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(kvPairs.size());
        String k, v;
        Iterator<String> itKeys = kvPairs.keySet().iterator();
        while (itKeys.hasNext()) {
            k = itKeys.next();
            v = kvPairs.get(k);
            nameValuePairs.add(new BasicNameValuePair(k, v));
        }
        httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs, "UTF-8"));
    }
    HttpResponse response;
    response = httpclient.execute(httppost);
    String responseString = EntityUtils.toString(response.getEntity());

Also need this method in your class

public static HttpClient getNewHttpClient() {
    try {
        KeyStore trustStore = KeyStore.getInstance(KeyStore.getDefaultType());
        trustStore.load(null, null);

        SSLSocketFactory sf = new RecorridoSSL(trustStore);
        sf.setHostnameVerifier(SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);

        HttpParams params = new BasicHttpParams();
        HttpProtocolParams.setVersion(params, HttpVersion.HTTP_1_1);
        HttpProtocolParams.setContentCharset(params, HTTP.UTF_8);

        SchemeRegistry registry = new SchemeRegistry();
        registry.register(new Scheme("http", PlainSocketFactory.getSocketFactory(), 80));
        registry.register(new Scheme("https", sf, 443));

        ClientConnectionManager ccm = new ThreadSafeClientConnManager(params, registry);

        return new DefaultHttpClient(ccm, params);
    } catch (Exception e) {
        return new DefaultHttpClient();
    }
}

hope I don't forgot anything, other way tell me

Comments

0

Guys the error was in my PHP

$device_token  = urldecode($_POST['regid']); 

This urldecode was messing out with my code haha

Thx for all help

Comments

-1
package com.example.project_name

import android.os.Bundle

import android.widget.TextView
import androidx.appcompat.app.AppCompatActivity

import com.android.volley.Response

import com.android.volley.toolbox.StringRequest
import com.android.volley.toolbox.Volley

class MainActivity : AppCompatActivity() {

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)

        val textView = findViewById<TextView>(R.id.textView)
        val url = "https://path/index.php"

        val queue = Volley.newRequestQueue(this)

        val stringRequest = object : StringRequest(
            Method.POST, url,
            Response.Listener { response ->
                textView.text = response!! // Changed 'e' to 'd' for debug logging
            },
            Response.ErrorListener { error ->
                textView.text = error.toString()
            }) {
            override fun getParams(): Map<String, String> {
                val params = HashMap<String, String>() // Use HashMap instead of deprecated HasMap
                params["key1"] = "hello" // No duplicate key
                params["key2"] = "world" // Added second key-value pair

                return params
            }

//            override fun getHeaders(): Map<String, String> {
//                return mapOf("Content-Type" to "application/x-www-form-urlencoded") // Corrected case for header key
//            }
        }

        queue.add(stringRequest)
    }
}

1 Comment

Your answer could be improved with additional supporting information. Please edit to add further details, such as citations or documentation, so that others can confirm that your answer is correct. You can find more information on how to write good answers in the help center.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.