Android: How to send HTTP GET request to Servlet using Apache Http Client

21 September 2012 By Nithya Vasudevan 36,233 views 22 Comments
10 Flares Twitter 0 Facebook 2 Google+ 8 10 Flares ×

Project Description

  • In this Android tutorial, we will see how to make a simple Http GET request to Servlet using Apache Http Client (DefaultHttpClient) and display the response in TextView.
  • We use android.os.AsyncTask to perform this task.

Environment Used


Servlet Project

Create a new Dynamic Web Project and name it as “HttpGetServlet“.


Create a new Servlet and name it as “HelloWorldServlet” in package “com.theopentutorials.servlets” and copy the following code.

package com.theopentutorials.servlets;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class HelloWorldServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;

	public HelloWorldServlet() {

	protected void doGet(HttpServletRequest request,
			HttpServletResponse response) 
			throws ServletException, IOException {
		PrintWriter out = response.getWriter();
		out.println("Hello Android !!!!");

Start server

Deploy the project in server and start/restart the server. You can refer the link mentioned in prerequisite section to do this.

Folder structure

The complete folder structure of this Servlet project is shown below.

Android Project

Create an Android project and name it as “SimpleHttpGetServlet“.


Open res/values/string.xml and replace it with following content.

<?xml version="1.0" encoding="utf-8"?>
    <string name="hello">Accessing Servlet from Android</string>
    <string name="app_name">SimpleHttpGetServlet</string>
    <string name="button">Invoke Servlet</string>

XML layout file

This application uses XML layout file (main.xml) to display the response from Servlet.

Open main.xml file in res/layout and copy the following content.

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android=""
    android:orientation="vertical" >

        android:text="@string/hello" />

        android:text="@string/button" />

        android:textStyle="bold" />



In src folder, create a new Class and name it as “HttpGetServletActivity” in the package “” and copy the following code.

From Android 3.x Honeycomb or later, you cannot perform Network IO on the UI thread and doing this throws android.os.NetworkOnMainThreadException. You must use Asynctask instead as shown below.


import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.util.EntityUtils;

import android.os.AsyncTask;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.TextView;

public class HttpGetServletActivity extends Activity implements OnClickListener{
	Button button;
	TextView outputText;
	public static final String URL = "";
    /** Called when the activity is first created. */
    public void onCreate(Bundle savedInstanceState) {


    private void findViewsById() {
		button = (Button) findViewById(;
		outputText = (TextView) findViewById(;
    public void onClick(View view) {
		GetXMLTask task = new GetXMLTask();
		task.execute(new String[] { URL });

    private class GetXMLTask extends AsyncTask<String, Void, String> {
		protected String doInBackground(String... urls) {
			String output = null;
			for (String url : urls) {
				output = getOutputFromUrl(url);
			return output;
    	private String getOutputFromUrl(String url) {
			String output = null;
			try {
				DefaultHttpClient httpClient = new DefaultHttpClient();
				HttpGet httpGet = new HttpGet(url);

				HttpResponse httpResponse = httpClient.execute(httpGet);
				HttpEntity httpEntity = httpResponse.getEntity();
				output = EntityUtils.toString(httpEntity);
			} catch (UnsupportedEncodingException e) {
			} catch (ClientProtocolException e) {
			} catch (IOException e) {
			return output;
		protected void onPostExecute(String output) {
  • Whenever we need to perform lengthy operation or any background operation we can use Asyntask which executes a task in background and publish results on the UI thread without having to manipulate threads and/or handlers.
  • In onClick(), we create and execute the task to make Http request and get response. The task’s execute method invokes doInBackground() where we use Apache Http Client API to execute the Http GET request to Servlet and get output response and return it.
  • Once the background computation finishes, onPostExecute() is invoked on the UI thread which sets the output text in TextView.

We are running the remote server in the local machine itself (localhost). So you may try to access the resources using http://localhost:8080, but you may get “Connection refused” (failed to connect to localhost/ exception because our code is running in an emulator so localhost refers to the emulator itself and not the machine which is running the Tomcat/Apache server. So to access local machine from emulator, you have to use IP address which points to the machine which has the running emulator.

Android includes two HTTP clients: HttpURLConnection and Apache HTTP Client.
For Gingerbread and later, HttpURLConnection is the best choice. Refer this link for HttpURLConnection example.


Define the activity in AndroidManifest.xml file. To access internet from Android application set the android.permission.INTERNET permission in manifest file as shown below.

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android=""
    android:versionName="1.0" >

    <uses-sdk android:minSdkVersion="15" />

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

        android:label="@string/app_name" >       
            android:label="@string/app_name" >
                <action android:name="android.intent.action.MAIN" />
                <category android:name="android.intent.category.LAUNCHER" />

Android Project Folder Structure

The complete folder structure of this example is shown below.


Run your Android application

Tags: , , , , , , ,

  • Rashi..Coorg..

    Nice one.. Thank u..

  • anny


  • Andi

    Thanks for the tutorial ,but what if we want to send a string from the android app to the servlet ?

  • Praveen Macherla

    Get the needed data to be send (value from text field, check box etc) and append it to the URL variable as query parameters.

    For eg, if you want to send name and addr, you can form URL like and from the servlet use request.getParameter(“name”) and so on.

  • surabhe

    what if i want to send a .vcf file ,to the server, how can i do that?

  • aiemen

    I want to send a message in parameters , it works the first time i click the button , but then i want to send again a second parameter .. it does not works then ! what should i do??

  • imran

    Hello Mam, Your tutorials are more useful. And my doubt : am using Eclipse ADT plugin, here I can’t find option for create Servlet. I want to create servlet for android projects.

    • Shubh

      plz read the 3.Prerequisites point of the project.
      The second point redirects you to servlet creation in eclipse.

  • Faizal

    Can you give me the Life cycle of this project?

  • Shubh

    nice tutorial simple and easy. and it works like a charm.
    I have one doubt what should i do to run this application from an android device with the help of wifi?

    • Nithya Vasudevan

      Instead of “″ IP address, give the machine’s IP address where the servlet has been deployed.

  • Secu

    Your tutorial is so useful. Simple with more Infos ))

    Thx , really great!

  • Secu

    So you use here this Link

    I have a Servlet where I use this HelloWorldServlet+ .JSP Files .. And it works when I give after HttpGetServlet/JspFile.jsp … But when I give HttpGetServlet/HelloWorldServlet -> 404 Not Found ….

    What Im doing Wrong?

  • Secu

    So I have the Answer to my Question ! :D

    Who can´t open the JavaClass… then test if in web.xml(Servlet) … you have that:





  • Secu

    hmm… FAIL :D here is HTML and its dont show !!
    so …who have same Problem … just whrite here -> [email protected]

  • eli

    Is the best tutorial tks

  • Balasaheb pawar

    Thanks sir, It is valueable tutorials for me but i want to send request throgh android App and using the JSON

  • Dilshad

    Without any doubt this is wonderful tutorial , i am aware with android but servelet is new for me. I am using this servlet code and ruing in browser i am getting error on browser “HTTP status 404/HttpGetServelet/”. And in android end it is timeout Exception. Both code(Android and servlet) are running on different system. That why i am using url as “”. is url of other system and 9999 is port number for server.So i will run this tutorial successfully and what is my fault.??
    Any help will be appreciated .

  • Anton

    I’m trying to pass a parameter from a text box:

    EditText editTextValue
    public String givenValue = editTextValue.getText (). toString ();
    public final String URL = "http://example/script.php?ip =" + givenvalue;

    But this is:

    ERROR / AndroidRuntime (7103): FATAL EXCEPTION: main
    at com.example.CableDiag.MainActivity. ( 39) (public String givenValue = editTextValue.getText (). toString () ;)

    How can I fix it?

    Sorry for my English.

  • Anand

    Thanks a lot !!!!

  • nik

    when i try to access the server through address from my real android device (usb connected), I am getting a conncetion refused error. when I run it from the emulator, it works fine. What am I doing wrong?

  • Elango

    Dear All,

    I have big issue with this code how to connect andriod mobile and system.This code not work with while i connect mobile and system.kindly assist.