Gets data from URL : Url « Network « Android






Gets data from URL

 
//package com.sabdroid.util;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;

import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.params.HttpConnectionParams;
import org.apache.http.params.HttpParams;

import android.util.Log;

public class HttpUtil
{
    private static HttpUtil _instance;
    private static DefaultHttpClient httpClient = new DefaultHttpClient();

    private HttpUtil()
    {
        HttpParams params = httpClient.getParams();
        HttpConnectionParams.setConnectionTimeout(params, 60000);
        HttpConnectionParams.setSoTimeout(params, 60000);
    }

    public static HttpUtil instance()
    {
        if (_instance == null)
            _instance = new HttpUtil();

        return _instance;
    }

    /**
     * Gets data from URL
     * throws {@link RuntimeException} If anything goes wrong
     * @throws ServerConnectinoException 
     */
    public String getData(String url) throws ServerConnectinoException
    {
        try
        {
            HttpGet request = new HttpGet(url);

            HttpResponse response = httpClient.execute(request);

            int status = response.getStatusLine().getStatusCode();

            if (status != HttpStatus.SC_OK)
            {
                throw new ServerConnectinoException("Connection Error: " + response.getStatusLine().getReasonPhrase());
            }
            else
            {
                InputStream content = response.getEntity().getContent();

                return inputStreamAsString(content);
            }
        }
        catch (ServerConnectinoException e)
        {
            throw new ServerConnectinoException(e.getMessage());
        }
        catch (IOException e)
        {
            throw new ServerConnectinoException("Connection timeout!");
        }
        catch (Throwable e)
        {
            Log.w("HTTP", "Failed to connect to server", e);
            throw new RuntimeException(e);
        }
    }

    public static String inputStreamAsString(InputStream stream) throws IOException
    {
        BufferedReader br = new BufferedReader(new InputStreamReader(stream));
        StringBuilder sb = new StringBuilder();
        String line = null;

        while ((line = br.readLine()) != null)
        {
            sb.append(line + "\n");
        }

        br.close();
        String result = sb.toString();
        stream.close();
        return result.substring(0, result.length() - 1);
    }

    public class ServerConnectinoException extends Exception
    {
        private static final long serialVersionUID = -7812290125811215338L;

        public ServerConnectinoException(String message)
        {
            super(message);
        }
    }
}

   
  








Related examples in the same category

1.Using Intent to open a URL
2.Process xml document from a Url
3.Suggest Url Provider
4.Showing android:autoLink property, which linkifies things like URLs and phone numbers found in the text.
5.extends ArrayAdapter to create URL history
6.Used to compress URL using the bit.ly service.
7.URL encode and decode
8.Is valid URL
9.Download from URLConnection
10.Request from an URL
11.Get Url From Img Tag
12.Returns the contents of the given URL as an array of strings
13.Read from a URL
14.Pull the raw text content of the given URL.
15.Get Video from URL
16.get Url Response
17.URL Encode Utils
18.Downloads a file given URL to specified destination
19.get Host From Url
20.encode Url
21.decode Url
22.Convert a byte array to a URL encoded string
23.get Url content with max retries
24.get Url By Post
25.Take a base url and a {@link Map} of parameters to build a valid url