Android: How to send HTTP GET request to Servlet using HttpURLConnection

21 September 2012 By Nithya Vasudevan 28,368 views 14 Comments
11 Flares Twitter 2 Facebook 4 Google+ 5 11 Flares ×

Project Description

  • In this Android tutorial, we will see how to make a simple Http GET request to Servlet using HttpURLConnection 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 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 HttpGetServletActivity3 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) {
			StringBuffer output = new StringBuffer("");
			try {
				InputStream stream = getHttpConnection(url);
				BufferedReader buffer = new BufferedReader(
						new InputStreamReader(stream));
				String s = "";
				while ((s = buffer.readLine()) != null)
			} catch (IOException e1) {
			return output.toString();

		// Makes HttpURLConnection and returns InputStream
		private InputStream getHttpConnection(String urlString)
				throws IOException {
			InputStream stream = null;
			URL url = new URL(urlString);
			URLConnection connection = url.openConnection();

			try {
				HttpURLConnection httpConnection = (HttpURLConnection) connection;

				if (httpConnection.getResponseCode() == HttpURLConnection.HTTP_OK) {
					stream = httpConnection.getInputStream();
			} catch (Exception ex) {
			return stream;

		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 open a Http URL connection using the given Servlet URL and get output response from InputStream 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 Apache HTTP Client example, if your application targets platform prior to Gingerbread.


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: , , , , , ,

  • devang

    plz, provide complete code ZIP file.


    Thank You
    Very much
    I think you have saved my job….

    Thanks once again..

  • amy

    This works like charm

  • Sheriffo

    Great Tutorial.

    I am working on something similar, my question is, is it possible for the invoked message e.g. in you case “Hello World” to come from Android.

    For example, entering any text in a text box send it to the servlet which will set the out.println(“Value Sent From Android Device”);. So basically dynamically setting the invoked string which has to come from the android device.

    • Nithya Vasudevan

      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.
      Or use POST method and add parameters.

      • Andi

        Thank you for your help :)

  • Michael

    Thank you for this tutorial. I spent like 4 hours at work looking for a good HttpURLConnection tutorial and none of them worked. This was easy to follow, nicely separated into methods/classes(Soooo many tutorials just slam all the code in one giant hard to read block… so annoying.), and best of all it just… works! Thank you!

  • sonu

    excellent tutorial…really helpful….

  • Anish

    Great tutorial!
    What changes would occur if we would want to make a POST request?
    I tried replacing GET with POST but that does not seem to work :(

    • Nithya Vasudevan

      Use this code for POST request.

      public JSONObject getJSONHttpURLConnection(String urlString,
      			List<NameValuePair> params) throws IOException, JSONException {
      		InputStream stream = null;
      		try {
      			URL url = new URL(urlString);
      			URLConnection connection = url.openConnection();
      			HttpURLConnection httpConnection = (HttpURLConnection) connection;
      			OutputStream os = httpConnection.getOutputStream();
      			BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(
      					os, "UTF-8"));
      			if (httpConnection.getResponseCode() == HttpURLConnection.HTTP_OK) {
      				stream = httpConnection.getInputStream();
      				json = getString(stream);
      				//Log.d("json", json);
      				jObj = new JSONObject(json);
      		} catch (IOException e) {
      			throw e;
      		} catch (JSONException e) {
      			throw e;
      		return jObj;
      	private String getQueryString(List<NameValuePair> params)
      			throws UnsupportedEncodingException {
      		StringBuilder result = new StringBuilder();
      		boolean first = true;
      		for (NameValuePair pair : params) {
      			if (first)
      				first = false;
      			result.append(URLEncoder.encode(pair.getName(), "UTF-8"));
      			result.append(URLEncoder.encode(pair.getValue(), "UTF-8"));
      		return result.toString();
  • sapan kumar das

    where i get URL =”http below code

    public static final String URL =

  • Ashley

    Hi Nithya,

    You have explained the entire tutorial very efficiently.
    But when I deploy the android application on the emulator, It stops working after the button click and gives an error “Error occurred while executing doInBackground() method”

    Can you please help me

    • Ashley

      I made a very silly mistake of not adding internet permission in manifest. Its working now.
      Great tutorial.
      Big thanks.


  • miko wong

    Thank you, this is great tutorial. The code is working fine. There are some part I don’t really understand. AsyncTask and this one (String… urls ), what does the three dot mean ? If i try to do a login by passing the parameters(username and password) and return the true/false, where can I place it ?