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.
Related
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.
I had some problem understanding the following line of code. What exactly does it do and how does it help me query the database from android
$q=mysql_query("SELECT * FROM people WHERE birthyear>'".$_REQUEST['year']."'");
while($e=mysql_fetch_assoc($q))
$output[]=$e;
print(json_encode($output));
I know the initial part of it means select every record from table people where birthyear...
But after that I get confused. I am calling this php function from android using http post
ArrayList<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
nameValuePairs.add(new BasicNameValuePair("year","1980"));
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost("http://10.0.2.2/retrieve.php");
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
HttpResponse response = httpclient.execute(httppost);
HttpEntity entity = response.getEntity();
is = entity.getContent();
Where is an input stream. Can someone help me out?
The PHP code queries the database and constructs a JSON output, which it sends to the calling client. Try calling the php from a browser (put the URL in the address bar) - and you should get the JSON back.
On the Android side, java code is using HTTPClient wrapper to call your php and get the response. Socket (HTTP connection) InputStream is handled internally by HttpClient when you call relevant methods. From your point of view, all you need to do is deal with the content of the entity.
You can just open the input stream from the entity (your is variable) and read the data from it:
InputStream is = entity.getContent();
then read the content of the stream as you normally would. You should get the json as was sent by the php.
PHP gets the value of required minimum year from year request parameter. In android, a NameValuePair is created with name=year and value=1980. This NameValuePair is passed as POST parameter in the form year=1980 to the PHP code. Again, this is handled internally by the HTTPClient wrapper class. Then the PHP code reads the value of request parameter "year" to get the minimum value for the query.
In the above code is is the instance of InputStream entity.getContent() returns InputStream type object. In the line is = entity.getContent(); is is the InputStream
I am trying to see what is wrong with a php script a wrote. The script is getting information from an android application and then using that data to search a table and send information back. The client side is written like this:
nameValuePairs.add(new BasicNameValuePair("num1", num1));
nameValuePairs.add(new BasicNameValuePair("num2", num2));
nameValuePairs.add(new BasicNameValuePair("num3", num3));
nameValuePairs.add(new BasicNameValuePair("num4", num4));
InputStream is = null;
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost("http://10.0.0.4/xampp/phpfile.php");
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
HttpResponse response = httpclient.execute(httppost);
HttpEntity entity = response.getEntity();
is = entity.getContent();
How do I format the url in a browser if I want to execute the same script passing num1, num2, num3 and num4 in the same way?
use http://hurl.it/ to test POST request from your browser...
Since you are using POST methos, as I can see, you can't call it from a browser url.
You can write a simple html file, with a form in it, wich uses post method, and then submit that.
Or modify the server side php file, and instead of using $_POST[] variables use $_REQUEST[] variables, wich accept both GET and POST method calls.
In this case:
http://10.0.0.4/xampp/phpfile.php?num1=num1&num2=num2...
should work fine.
I am trying to post a string to a php file on my web server from my android phone. I am able to establish a connection to the file, as I can retrieve what it prints. The problem I am having is sending the POST variable, which continually seems to be null(I am testing the program now, and sending back what the POST variable is). Here is the relevant code:
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost(HTTP://WWW....PHP FILE ADDRESS);
try{
// the data to send
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
nameValuePairs.add(new BasicNameValuePair("RoomName", "HELLO"));//params[1]
// http post
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs, HTTP.UTF_8));
HttpResponse response = httpclient.execute(httppost);
HttpEntity entity = response.getEntity();
InputStream is = entity.getContent();
My PHP code is (at the moment) as follows:
$roomname = $_POST['RoomName'];
$returnArray[] = array("LoggedIn" => $roomname);
print_r(json_encode($returnArray));
I have been looking at forums for the past week, and all the httppost examples follow this almost exactly. I would appreciate any help that you are willing to give. Thanks a lot
Well, try $_REQUEST in place $_POST.
i have been trying to call a PHP script with the android system. i am using Eclipse helio and everything else i have written works fine on it - not much yet. so i block copied this code and it does not work: i have no warnings or errors and i can debug and step through it, but it always comes back with
"E log_tag : Error in http connection java.net.UnknownHostException: www.X.com"
here is the code:
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(2);
nameValuePairs.add(new BasicNameValuePair("Lat","19.80"));
nameValuePairs.add(new BasicNameValuePair("Lon","13.22"));
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost("http://www.X.com/new/getAllPeopleBornAfter.php");
try{
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
HttpResponse response = httpclient.execute(httppost);
HttpEntity entity = response.getEntity();
InputStream is = entity.getContent();
Log.i("postData", response.getStatusLine().toString());
}
catch(Exception e)
{
Log.e("log_tag", "Error in http connection "+e.toString());
}
and the PHP which runs fine if i go there with a browser:
mysql_connect("mysql27.x.com","name","PW");
mysql_select_db("dbname");
$q = mysql_query("SELECT * FROM people");
while ($e = mysql_fetch_assoc($q)) $output[] = $e;
mysql_close();
echo (json_encode($output));
?>
if you guys want me to run anything in a different format or any more info - please let me know - i cant find any thing more than just unknownhostexception
Can you access www.X.com from the emulator/phone?
Do you have the INTERNET permission?
Did you remember to put:
<uses-permission android:name="android.permission.INTERNET"></uses-permission>
into your manifest file?
Are you behind a proxy network? Should you be setting the proxy ip address and port number? I'm no good with php. But I get this error when I try to connect to the internet through java programs. The solution works good for me.