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.

Implementation:

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

import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
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;
import java.io.IOException;

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) {
				str.append(line);
			}
			in.close();
			html = str.toString();

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

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

Conclusion:

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

18,829 total views, 1 views today

(Visited 1,715 times, 1 visits today)