Is there any method to get data from an Android app to a website?
If it is from website to website, with "file_get_contents" it is possible. But then any idea on getting data from Android apps?
Thanks in advance!
Using this simple php script you can get data from android:
<?php
$filename="datatest.html";
file_put_contents($filename,$_POST["fname"]."<br />",FILE_APPEND);
file_put_contents($filename,$_POST["fphone"]."<br />",FILE_APPEND);
file_put_contents($filename,$_POST["femail"]."<br />",FILE_APPEND);
file_put_contents($filename,$_POST["fcomment"]."<br />",FILE_APPEND);
$msg=file_get_contents($filename);
echo $msg; ?>
In android can use HttpPost to accomplish this by something like this:
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost("http://example.com/mypage.php");
try {
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(4);
nameValuePairs.add(new BasicNameValuePair("fname", "jake"));
nameValuePairs.add(new BasicNameValuePair("fphone", "9999999"));
nameValuePairs.add(new BasicNameValuePair("femail", "xyz#live.com"));
nameValuePairs.add(new BasicNameValuePair("fcomment", "Help"));
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
httpclient.execute(httppost);
} catch (ClientProtocolException e) {
// TODO Auto-generated catch block
} catch (IOException e) {
// TODO Auto-generated catch block
}
Replace your data with the fields you want to set and send in the constructor of BasicNameValuePair.
Here is the actual Source
You could execute post requests in android to your website. Although this has to executed from a different thread, since android doesn't allow network operations on the main thread.
Related
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
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
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
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.