Android HttpPost send empty $_POST to a PHP script - php

I have been trying to send a POST request to a URL from my Android App, but all that I get is a empty $_POST. Here is my code, it is running inside a Asynctask. I looked at several issues like this here in the StackOverflow, but none of them could help me.
HttpClient httpClient = new DefaultHttpClient();
HttpPost post = new HttpPost("http://www.somesite.com/clients/app-controller/posts.php");
try {
List<NameValuePair> pairs = new ArrayList<NameValuePair>();
pairs.add(new BasicNameValuePair("id", "12345"));
pairs.add(new BasicNameValuePair("name", "John"));
pairs.add(new BasicNameValuePair("post", "test123"));
post.setEntity(new UrlEncodedFormEntity(pairs, HTTP.UTF_8));
post.setHeader("Content-Type", "application/x-www-form-urlencoded");
HttpResponse response = httpClient.execute(post);
String text = EntityUtils.toString(response.getEntity());
System.out.println("STATUS CODE " + response.getStatusLine().getStatusCode());
System.out.println("RETURN " + text);
} catch (ClientProtocolException e) {
System.out.println("ERROR1: " + e.getStackTrace());
} catch (IOException e) {
System.out.println("ERROR2: " + e.getStackTrace());
}
On the server side, I have a PHP test script testing if the $_POST variable are OK.
<?php echo "ISSET = " . isset($_POST["id"]) . isset($_POST["name"]) . isset($_POST["post"]); ?>
All that I get is a not set $_POST
STATUS CODE 200
RETURN ISSET =
I don't get any error warning and the App doesn't crash.
I tried to put the variables as a GET request attached to the URL and changed my PHP file to process the the $_GET request:
HttpPost post = new HttpPost("http://www.somesite.com/clients/app-controller/posts.php?id=1234&name=John&post=test123");
It worked fine. I could read all $_GET variables in the PHP script. But I need it to be a POST request.
I have the INTERNET permission in my AndroidManifest.xml. In this same App I do requests for another PHP script and it work as expected.
<uses-permission android:name="android.permission.INTERNET" />
Any thoughts?

If your HttpPost URL has "www" remove it and try. If not add www.
Because, you might have redirected yoursite.com to www.yoursite.com or vice versa. In such cases, your HttpPost URL should be the designation URL and not the redirecting URL. The parameters will be lost during the HTTP redirection process and a empty POST will be done. This is why the server is not receiving your post data.

Related

android - Parallel task to execute PHP on server

I'm developping and android application and in some point I need to get some vaue from my server. This server has a simple PHP script that just echo a value.
In order to do it, that's what I do:
private static String executePHP(String URL) {
// Create a new HttpClient and Post Header
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost(URL);
try {
// Execute HTTP Post Request
ResponseHandler<String> responseHandler = new BasicResponseHandler();
String response = httpclient.execute(httppost, responseHandler);
return(response);
} catch (IOException e) {
// TODO Auto-generated catch block
return("");
}
}
The method is static, because I call it upon an SMS arrives. Then the URL comes from the SMS text.
From the broadcastReceiver I call:
MainActivity.executePHP(link);
I want the execution of the PHP to be on a background task.
I've been reading of AsyncTask but they need and instance, which I don't have.
What's the best way to do it??
Also, have in mind that the application may not be active right now.
I'll be happy if I can only Toast the result from the PHP executing on asyncTask (or other asyncrhonus thread).
Thanks you all!!
Have a nice day!
Finally, this solve my question! Now I need to see how to handle no-internet-connection.
solution

How to make a web service (preferably using PHP) that can be requested to get JSON objects by the android app

I am making an Android App which interacts with remote server's database and communicate with each other by passing JSON object to and from.
I need to know how to write such a service on my server (preferably in PHP) to which the android app can make request and on receiving the request, the server processes and makes a JSON object and passes that to the android app.
Also, i need to know, when this service is running on the server, on WHICH URL will the android app make request?
For example, if android app have to request to sever to fetch data for parameters:
name: Apple
location: US
then, i guess the android app will have to request the server in form of:
www.example.com?name='Apple"&location='US'
So how to make such a service running on the remote server?
Thanks in advance !
The best example you can refer for this is http://www.androidhive.info/2012/01/android-login-and-registration-with-php-mysql-and-sqlite/. It has complete code[php+ android] with simple explanation.
You can write a method that request remote php file that responses to post or get request. if you want to use post request , you can use method below. and you have to add Internet permisson to your manifest file. As you see below , you can add parameters as being key -value pair.
public void postData() {
// Create a new HttpClient and Post Header
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost("http://www.yoursite.com/webservice.php");
try {
// Add your data
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(2);
nameValuePairs.add(new BasicNameValuePair("name", "Apple"));
nameValuePairs.add(new BasicNameValuePair("locaction", "US"));
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
ResponseHandler <String> res=new BasicResponseHandler();
// Execute HTTP Post Request
String response = httpclient.execute(httppost,res);
} catch (ClientProtocolException e) {
// TODO Auto-generated catch block
} catch (IOException e) {
// TODO Auto-generated catch block
}
}
http://www.androidsnippets.com/executing-a-http-post-request-with-httpclient

Android to PHP error- Unidentified Index

when sending data to a php server through android I cam across this error: "Notice: Undefined index: IT in C:\xampp\htdocs\hello.php on line 4". After a few hours of messing around with it I can't solve my issue.
hello.php :
<?php
mysql_connect("localhost","user","pass");
mysql_select_db("mmo");
$r=mysql_query("update players set X = '".$_REQUEST['IT']."' where 22=22");
if(!$r)
echo "Error in query: ".mysql_error();
mysql_close();
header('Refresh: 0.01; URL=http://localhost/hello.php');
?>
update method in android:
public void UpdateSeverWithPlayer()
{List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
nameValuePairs.add(new BasicNameValuePair("IT","3"));
try{
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost("http://10.0.2.2/hello.php");
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
HttpResponse response = httpclient.execute(httppost);
HttpEntity entity = response.getEntity();
is = entity.getContent();
}catch(Exception e){
Log.e("log_tag", "Error in http connection"+e.toString());
}}
I am working on the android emulator and do have the internet permission. As always help is greatly appreciated.
EDIT 1: It appears the issue is in the android and not the php code.
You're not sending your query string propertly somehow, so there is no $_REQUEST['IT'] on the PHP side. do a var_dump($_REQUEST) to see what's coming through. Or better yet, don't use $_REQUEST. It's somewhat insecure. Better use the superglobal directly related to your HTTP method, _GET or _POST.
As well, the Refresh header is non-standard. it'll work, but you shouldn't depend on it. An HTTP level redirect uses the Location: header. Refresh: is a non-standard old-school Netscape extension.

Get POST data on Webpage from Android-App?

I am trying to output POST-data that I send from an android phone, however I cannot manage to get any output in my PHP file.
This is my php code:
<?php
echo "POSTed data: '".$_POST['mydata']."'<br>";
var_dump($_POST);
?>
this is my android code (which seems to work fine)
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost("myurl.php");
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(2);
nameValuePairs.add(new BasicNameValuePair("mydata", "12345"));
nameValuePairs.add(new BasicNameValuePair("stringData", "SomeData"));
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
// Execute HTTP Post Request
HttpResponse response = httpclient.execute(httppost);
String responseText = EntityUtils.toString(response.getEntity());
toSendET.setText(responseText);
Is it even possible to send POST data to an static PHP script via phone?
What you have got is working fine - but when you echo something in PHP its echo'd back to the caller - ie the browser in this case.
If you check the value of response in the code on Android is will be POSTed data: '12344'<br>
See the error_log() function in PHP for logging to a file

Sending information from android app to a php script

I'm neither a android or php expert, the thing is that I made a php script that gets the variables from the url ( www.myhost.com/mailScript.php?variable1=name&variable2=age ) and sends a mail with that information.
Mail:
Variable1=Name
Variable2=Age
Now, the problem is that i'm makin a android app that converts a normal form, which ask name, age, etc. And i want to take that information and run php script. But i dont want the users to see a web browser at any time, just that they click de button, get the info, run the url, and done.
The easiest way to do it is mentioned here. Basically, you just want to form the URL based on the value of each of your fields, then hit that URL with an HTTP request.
Use JSON to send data to your PHP script.
By combining that
public void postData() {
// Create a new HttpClient and Post Header
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost("http://www.yoursite.com/script.php");
try {
// Add your data
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(2);
nameValuePairs.add(new BasicNameValuePair("id", "12345"));
nameValuePairs.add(new BasicNameValuePair("stringdata", "AndDev is Cool!"));
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
// Execute HTTP Post Request
HttpResponse response = httpclient.execute(httppost);
} catch (ClientProtocolException e) {
// TODO Auto-generated catch block
} catch (IOException e) {
// TODO Auto-generated catch block
}
}
Source : http://www.androidsnippets.com/executing-a-http-post-request-with-httpclient
and looking about JSON, you should be able to do what you want
your php will be the server side and your android application will the be the client side you will just create a form using normal android's UI widgets. There's a plenty of examples around and send your data via HttpPost or HttpGet classes with your parameters set from this form.
http://mobile.tutsplus.com/tutorials/android/android-sdk-creating-forms/
and posting example Secure HTTP Post in Android

Categories