Sending information from android app to a php script - php

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

Related

How to call a PHP based web-service from Android?

I have a simple PHP web-service which return result as JSON .
if($_SERVER["REQUEST_METHOD"]=="POST"){
$arg1=$_POST["arg1"];
processArgs($arg1);
}
processArgs($arg1){
$result=doSomething($arg1);
echo json_encode($result);
}
I could call it from Android side using HttpURLConnection. But the problem is HttpURLConnection seems to be a work in very low level. Is there any level implementation which we could avoid writing the same code for making it asynchronous and for parsing the result.
Simply use HttpClient as follows.
HttpClient httpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost("http://your-host/comm.php");
try {
//add your post data
List<NameValuePair> args = new ArrayList<NameValuePair>(2);
args.add(new BasicNameValuePair("arg1", "your-arg-1"));
httpPost.setEntity(new UrlEncodedFormEntity(args));
//send your request
HttpResponse response = httpClient.execute(httpPost);
} catch (ClientProtocolException | IOException e) {
e.printStackTrace();
}
HttpURLConnection (java.net.HttpURLConnection) is the default HTTP client in Android.
OkHttp, is another one which became the engine that powers HttpUrlConnection as of Android 4.4. It is offers easier method to customize each requests.
Both HttpURLConnection and OkHttp works at somewhat low level. So we need to write our own code for making it asynchronous and for parsing the result again and again.
Retrofit, on the other hand, is a high level implementation which uses OkHttp for connection and Gson for parsing result. It can be used to turn HTTP APIs into a Java interface with ease.
Therefore, Retrofit would be the best choice unless you have specific reason to go with OkHttp ( Like HTTP-based streaming).

Retrieve data from android app to PHP website

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.

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

How do I send data in a url to test a php file?

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.

Categories