Introduction
Connection from an Android App to a web page sending parameters by POST
and getting the result is useful for example to recover information to make changes to an external database.
(Sorry for my English!)
Using the Code
First, we create the HTTPHandler
class that does the connection to the web page:
import java.util.List;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.util.EntityUtils;
import android.os.AsyncTask;
public class HTTPHandler {
@SuppressWarnings("deprecation")
public static String HTTPPost(String url,List<? extends NameValuePair> params)
{
String text ="";
try
{
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost(url);
httppost.setEntity(new UrlEncodedFormEntity(params));
HttpResponse resp = httpclient.execute(httppost);
HttpEntity ent = resp.getEntity();
text= EntityUtils.toString(ent);
}
catch (Exception e)
{
text=e.getCause().getMessage();
}
return text;
}
}
This class has a static
method for connecting to the URL, it gets a parameter list that sends to the URL.
Now we make an interface that help us to process the result of the call when the connection ends, the calls in Android must be realized into an asynchronous thread, for security Android doesn't permit to do some operations in the main thread.
public interface EventTaskAsyncFinish{
void finish(String res);
}
Now create the class conHTML
for managing connection to web page and return the result.
import java.util.ArrayList;
import java.util.List;
import org.apache.http.NameValuePair;
import android.os.AsyncTask;
public class conHTML {
private String url;
private List<NameValuePair> parametros;
private boolean waitFotFinish;
private ArrayList<EventTaskAsyncFinish>
EventTaskAsyncFinishObservers = new ArrayList<EventTaskAsyncFinish>();
public conHTML(String parUrl,List<NameValuePair> pars)
{
url=parUrl;
parametros=pars;
}
public void setEventTaskAsyncFinish(EventTaskAsyncFinish observer){
EventTaskAsyncFinishObservers.add(observer);
}
public void connect()
{
class TareaAsync extends AsyncTask<Void, Void, String>
{
private String url;
private List<NameValuePair> parametros;
public TareaAsync(String parUrl,List<NameValuePair> pars)
{
url=parUrl;
parametros=pars;
}
@Override
protected void onPostExecute(String result)
{
super.onPostExecute(result);
for (EventTaskAsyncFinish eventHappenedObserver:EventTaskAsyncFinishObservers){
eventHappenedObserver.finish(result);
}
}
@Override
protected String doInBackground(Void... params)
{
String resp=HTTPHandler.HTTPPost(url, parametros);
if (resp==null)
resp="NO RESPONSE";
return resp;
}
}
TareaAsync l=new TareaAsync(url,parametros);
l.execute();
}
}
We can see the class constructor gets the URL to the web page and a List of parameters that will be sent by POST
to the URL.
Always, the class has an Array of our interface (EventTaskAsyncFinishObservers
), and a method called setEventTaskAsyncFinish
for adding new EventTaskAsyncFinishObservers
to the object, this event will be triggered when the operation ends (see onPostExecute
method).
Finally, in our Android activities, we can use the method connect conHTML
to make connections in one glance and get the result. For example:
List<NameValuePair> params1 = new ArrayList<NameValuePair>();
params1.add(new BasicNameValuePair("user","uservalue"));
params1.add(new BasicNameValuePair("pass","passwordvalue"));
conHTML php=new conHTML(url+"login.php", params1);
php.setEventTaskAsyncFinish(new EventTaskAsyncFinish() {
@Override
public void finish(String res) {
ponerRespuesta(res);
}
});
php.connect();
In this example, I use a PHP web page with this code:
<?php
if (isset($_POST["user"]) && isset($_POST["pass"]))
{
$user=$_POST["user"];
$pass=$_POST["pass"];
if ($user=="" && $pass=="")
{
echo "Invalid parameters";
}
else
{
echo $user."\n".$pass;
}
}
else
{
echo "No parameters found";
}
?>
Points of Interest
Actually, some classes used in the example are marked as deprecated.