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

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).

Related

get string from php json encode to android target api23+

I have a php file that generates data that must take to Android.
This is the file output .php
[{"item":"1","title":"Title of one","link":"qwerty1234"},{"item":"2","title":"Title of two","link":"qwerty1234"},{"item":"3","title":"Title of three","link":"qwerty1234"}]
Now there have been changes with the class apache: Link here
Looking around I find several guides on the old method but I wanted to use the new one since my app is the targetSdkVersion 23.
I think this is the new method with JsonReader and HttpURLConnection.
I tried but I can not make it work or understand how to handle it.
So I ask, how do I take the strings from php page that creates? (example: title and link)
please try this.
it's working for me.
String url = "someurl.php";
HttpPost httppost = new HttpPost(url);
// Creating HTTP client
HttpClient httpClient = new DefaultHttpClient();
try {
HttpResponse response = httpClient.execute(httpPost);
String responseString = EntityUtils.toString(response.getEntity());
JSONObject jsonObject = new JSONObject(responseString);
String error = jsonObject.getString("item1");
} catch (IOException e) {
e.printStackTrace();
}
in this case i was using GSON to later parse the response but you can parse it as you wish.
this is a snippet of code that i can provide, if you need more help or if some dependencies are missing please tell me so i can point you in the right direction.
have a look at this tutorial for more help
http://www.codeproject.com/Articles/267023/Send-and-receive-json-between-android-and-php
if you need a webservice PHP framework, take a look at this
http://www.slimframework.com/
it's very easy to use and ligthweight framework so you can use it as a service to send and recieve info from your server
hope it helps, feel free to ask if you need any more help
cheers

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 communicate from php to Android

I am making a location application, where user can parameter some function from the server, so I want the server to begin a communication with the phone of the user.
But firstly, I want to open a communication with an android, from the php.
Is there a way to communicate with an android phone from a php server?
I already use the communication from android with HTTP to server with return of JSONObject, but I cant find anything for a php call to android.
I think its exactly like the application which can make your phone ring.
Check out Google Cloud Messaging for Android.
Google Cloud Messaging for Android (GCM) is a service that allows you to send data from your server to your users' Android-powered device. This could be a lightweight message telling your app there is new data to be fetched from the server (for instance, a movie uploaded by a friend), or it could be a message containing up to 4kb of payload data (so apps like instant messaging can consume the message directly).
The GET method
You will need to have the Android client connect to your server and pass your JSON messages. If the client needs to get some data from the server and disconnect, then you can just use a normal HTTP type GET.
The WebSocket method
If however, you decide you need a long running TCP connection passing JSON bidirectionally then you should consider something like WebSockets. I have written an Android WebSocket demo. The Android client by default connects to the websocket.org echo server, but that can be easily changed.
I also found a PHP WebSockets implementation.
The Push Method
Now if your plan is to push messages from the server to the client without the client initiating the connection you will need something like GCM (Google Cloud Messaging). Here is an article covering GCM and PHP.
Generally, creating connection from server side to client side is complex, because:
The client might use private IP address.
Inbound connection might be rejected if the device connected behind firewall.
You need to install an application if that can be run in the background and watches the server for new messages.
Using Web:
It depends on the browser how it support JavaScript API especially new HTML5 features such as Server Sent Events
To enable servers to push data to Web pages over HTTP or using
dedicated server-push protocols, this specification introduces the
EventSource interface.
Please use below link for store data in mysql using php and u need to create webservice in that you will get two response from php server
1) Json
2) xml
if you show example please visit below link
Creating a basic web services in php
also visit this link for better description
http://phpmaster.com/lets-talk-1/
You Can Use HTTpReq class :
public class HttpReq {
public String send (String url){
//send a http request and get the result
InputStream is = null;
String result = "";
try{
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost(url);
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());
}
try
{
BufferedReader reader = new BufferedReader(new InputStreamReader(is),8);
StringBuilder sb = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null)
{
sb.append(line + "\n");
}
is.close();
result=sb.toString();
}catch(Exception e){
Log.e("log_tag", "Error converting result " + e.toString());
}
return result;
}
}
Then you use this class to make connection and to call your php file to get the data as JSonObject .
ht = new HttpReq();
// send a http request with GET
x=ht.send("http://10.0.2.2/myFolder/myFile.php");
JSONArray jArray;
JSONObject json_data;
String h[]=x.split("<");
try {
jArray = new JSONArray(h[0]);
json_data = jArray.getJSONObject(0);
url=json_data.getString("url");
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
In Your Php file you may use this methods to get the JSon data or to send it to the android App
Json_decode($string);
And
Json_encode($string);
I hope that will help you :)

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

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