Get the content of a file from a URL as a string in Java. (Handling HTTP request in Android)

By | August 28, 2015

In this tutorial we will learn to get the contents of any file present at some url by making http request.

Use case:

  • JSON/XML parsing : If you want to send some data from server to your android app then the data can be printed as a string in JSON/XML format. This string then can be parsed by your android app to get the data.


Make the following imports in your .java class where you want to get the string.

import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;

We will used inbuilt classes and methods present in android for handling HTTP request to do our task.

Now create a new function getInternetData() and copy the content as shown below:

public String getInternetData(String url) throws Exception {
		String html = "";
		HttpClient client = new DefaultHttpClient();
		HttpGet request = new HttpGet(url);
		HttpResponse response;
		try {
			response = client.execute(request);
			int statuscode = response.getStatusLine().getStatusCode();

			InputStream in = response.getEntity().getContent();
			BufferedReader reader = new BufferedReader(
					new InputStreamReader(in));
			StringBuilder str = new StringBuilder();
			String line = null;
			while ((line = reader.readLine()) != null) {
			html = str.toString();

		} catch (ClientProtocolException e2) {		
		} catch (IOException e2) {
		return html;

The above function will return the string content of the file present at the given url to the function as a parameter.


You can simply use this function and get the string to parse JSON data or do any other work you want with that string.

21,505 total views, 1 views today

(Visited 1,972 times, 1 visits today)