Ala Varos
Ala Varos

Reputation: 1725

Not receiving params in PHP from Android POST

I'm trying to do a login AsyncTask in Android, through a POST request, but in my PHP code i'm not receiving any params, this is my code.

In my Android code:

HttpClient httpClient = new DefaultHttpClient();
HttpPost post = new HttpPost(Constants.MY_URL);
post.setHeader("content-type", "application/json");

JSONObject data = new JSONObject();
data.put("user", mUsername);
data.put("password", mPassword);
StringEntity entity = new StringEntity(data.toString());
post.setEntity(entity);

HttpResponse resp = httpClient.execute(post);
String respStr = EntityUtils.toString(resp.getEntity());

In PHP code:

$params = $this->getService()->getRequest()->getActionParams();
echo json_encode($params);

But in $params there is nothing, maybe I need to set other headers to the request, or maybe I have to send the params in a different way. Any idea?

I've also tried with:

echo json_encode($_POST);

But I get the same, nothing.

Thanks in advance!

Greetings.

UPDATE:

I've just tried with:

List<NameValuePair> pairs = new ArrayList<NameValuePair>();
pairs.add(new BasicNameValuePair("user", mUsername));
pairs.add(new BasicNameValuePair("password", mPassword));
post.setEntity(new UrlEncodedFormEntity(pairs));
ResponseHandler<String> handler = new BasicResponseHandler();
final String response = client.execute(post, handler);

And I get the same response, nothing, what am I doing wrong?

Upvotes: 1

Views: 740

Answers (2)

Ala Varos
Ala Varos

Reputation: 1725

I found my mistake, I only had to remove this line:

post.setHeader("content-type", "application/json");

And I had to use what jk2praj answered:

List<NameValuePair> pairs = new ArrayList<NameValuePair>();
pairs.add(new BasicNameValuePair("user", mUsername));
pairs.add(new BasicNameValuePair("password", mPassword));
post.setEntity(new UrlEncodedFormEntity(pairs));

Thanks jk2praj and user20232359723568423357842364 for your answers.

Greetings.

Upvotes: 1

Jitendra Prajapati
Jitendra Prajapati

Reputation: 1163

Use nameValuepair to send data to php

 List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
        nameValuePairs.add(new BasicNameValuePair("user", 
         txtUser.getText().toString()));
        nameValuePairs.add(new BasicNameValuePair("password",   
            txtPass.getText().toString()));
           httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
        ResponseHandler<String> responseHandler = new BasicResponseHandler();
        final String response = httpclient.execute(httppost,
                responseHandler);

Upvotes: 1

Related Questions