Simple Client Server Communication in android.
In this tutorial I’ll be assuming that you at least:
Have a basic knowledge of android
Have already developed a few small android application
I’ll be using the default HttpClient from org.apache.http package.
Client server communication is this much simple when it comes to android.
Create HttpClient with the default constructor.
Create a HttpGet or HttpPost object depending upon your needs, in this case I made a GET object so that we can know whats going on.
Initialize the object with a GET or POST url.
Execute the GET/POST object through the Http and you’ll get the server’s response in the response object of HttpResponse.
HttpClient httpclient = new DefaultHttpClient();
HttpGet httpget = new HttpGet("YOUR URL");
try {
HttpResponse response = httpclient.execute(httpget);
if(response != null) {
String line = "";
InputStream inputstream = response.getEntity().getContent();
line = convertStreamToString(inputstream);
Toast.makeText(this, line, Toast.LENGTH_SHORT).show();
} else {
Toast.makeText(this, "Unable to complete your request", Toast.LENGTH_LONG).show();
}
} catch (ClientProtocolException e) {
Toast.makeText(this, "Caught ClientProtocolException", Toast.LENGTH_SHORT).show();
} catch (IOException e) {
Toast.makeText(this, "Caught IOException", Toast.LENGTH_SHORT).show();
} catch (Exception e) {
Toast.makeText(this, "Caught Exception", Toast.LENGTH_SHORT).show();
}
In this tutorial I’ll be assuming that you at least:
Have a basic knowledge of android
Have already developed a few small android application
I’ll be using the default HttpClient from org.apache.http package.
Client server communication is this much simple when it comes to android.
Create HttpClient with the default constructor.
Create a HttpGet or HttpPost object depending upon your needs, in this case I made a GET object so that we can know whats going on.
Initialize the object with a GET or POST url.
Execute the GET/POST object through the Http and you’ll get the server’s response in the response object of HttpResponse.
Get data from server.
HttpGet httpget = new HttpGet("YOUR URL");
try {
HttpResponse response = httpclient.execute(httpget);
if(response != null) {
String line = "";
InputStream inputstream = response.getEntity().getContent();
line = convertStreamToString(inputstream);
Toast.makeText(this, line, Toast.LENGTH_SHORT).show();
} else {
Toast.makeText(this, "Unable to complete your request", Toast.LENGTH_LONG).show();
}
} catch (ClientProtocolException e) {
Toast.makeText(this, "Caught ClientProtocolException", Toast.LENGTH_SHORT).show();
} catch (IOException e) {
Toast.makeText(this, "Caught IOException", Toast.LENGTH_SHORT).show();
} catch (Exception e) {
Toast.makeText(this, "Caught Exception", Toast.LENGTH_SHORT).show();
}
No comments:
Post a Comment