As now in almost every Android Application, it is required to either send the data to a web server or fetch data from the web server. Where as in some cases you want to perform both the tasks. So, here i am going to tell you, how you can post some data to a web server and fetch the data as the server response in an Android Application. The code is very simple and easy.

Step 1. Creating HTTP client:-

HttpClient httpClient = new DefaultHttpClient();

This is Http Client which sends data to a web server either by Get method or by Post method and receives the server response. You can also use it to download a web page, image, video, zip or any utility over web. Similar to the CURL method of PHP.

Step 2. Creating the request method type:-

HttpPost httpPost = new HttpPost("http://www.7tech.co.in/");

This creates a Post type Http method request for to the site http://www.7tech.co.in/
Use HttpGet instead of HttpPost if you want to use the Get method.

Step 3. Setting up the parameters to be send with the post request:-

List<NameValuePair> params = new ArrayList(2);
params.add(new BasicNameValuePair("param1", "value1"));
params.add(new BasicNameValuePair("param2","value2"));
try {
	httpPost.setEntity(new UrlEncodedFormEntity(params));
} catch (UnsupportedEncodingException e) {
	e.printStackTrace();
}

This creates the parameters/data which will be send with the post request to the web server. The parameters should be URL encoded. That’s why we used “UrlEncodedFormEntity” method. This method throws an error “UnsupportedEncodingException”. So it needs to be put inside the try, catch.

Step 4. Executing HTTP Request

try {
	HttpResponse response = httpClient.execute(httpPost);
	int statusCode = response.getStatusLine().getStatusCode();
	if (statusCode != HttpStatus.SC_OK) {
		throw new Exception("HTTP status code: " + statusCode + " != " + HttpStatus.SC_OK);
	}
	//-------- Response received successfully. Here play with the data received ---------
} catch (ClientProtocolException e) {
	e.printStackTrace();
} catch (IOException e) {
	e.printStackTrace();
} catch (Exception e) {
	e.printStackTrace();
}

Here we executes the HTTP Request and receives the server response. We also checked whether the request has been executed without any error by checking the statuscode. This code throws some exceptions. So we have used the try catch for exception handling.

Step 5. Reading server response:-

HttpEntity entity= response.getEntity();
Reader reader = new InputStreamReader(new BufferedInputStream(entity.getContent()));
BufferedReader br=new BufferedReader(reader);
String line = null;
String res=null;
while ((line = br.readLine()) != null) {
	res+=line;
}
Toast.makeText(getApplicationContext(), res , Toast.LENGTH_LONG).show();

In this step, we are reading the server response as a string and displaying it to the user using Toast.

Here is the final code:-

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
HttpClient httpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost("http://www.7tech.co.in/");
List<NameValuePair> params = new ArrayList(2);
params.add(new BasicNameValuePair("param1", "value1"));
params.add(new BasicNameValuePair("param2","value2"));
try {
	httpPost.setEntity(new UrlEncodedFormEntity(params));
} catch (UnsupportedEncodingException e) {
	e.printStackTrace();
}
 
try {
	HttpResponse response = httpClient.execute(httpPost);
	int statusCode = response.getStatusLine().getStatusCode();
	if (statusCode != HttpStatus.SC_OK) {
		throw new Exception("HTTP status code: " + statusCode + " != " + HttpStatus.SC_OK);
	}
	HttpEntity entity= response.getEntity();
	Reader reader = new InputStreamReader(new BufferedInputStream(entity.getContent()));
	BufferedReader br=new BufferedReader(reader);
	String line = null;
	String res=null;
	while ((line = br.readLine()) != null) {
		res+=line;
	}
	Toast.makeText(getApplicationContext(), res , Toast.LENGTH_LONG).show();
} catch (ClientProtocolException e) {
	e.printStackTrace();
} catch (IOException e) {
	e.printStackTrace();
} catch (Exception e) {
	e.printStackTrace();
}

PS:- Don’t forget to add the user Internet permission in your AndroidManifest.xml file.
Add this:-

<uses-permission android:name="android.permission.INTERNET"></uses-permission>

before the <appliaction> tag