Request from an URL : Url « Network « Android






Request from an URL

 
/*
 * TepcoMeter:HttpUtils.java
 * Copyright  2011 ho9ho9 All Rights Reserved.
 */
//package com.ho9ho9.tepcometer.util;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;

import android.util.Log;

/**
 * Http????????????.
 * @author ho9ho9
 */
class HttpUtils {
  
  /** HTTP_METHOD_GET. */
  private static final String HTTP_METHOD_GET = "GET";
  private static final String TAG_NAME = "TepcoMetterWidgetService";
  
  public static String get(String url) {
    Log.d(TAG_NAME, "url:" + url);
    return request(url, HTTP_METHOD_GET);
  }
  private static String request(String url, String method) {
    String result = null;
    HttpURLConnection con = null;
    BufferedReader reader = null;
    try {
      con = (HttpURLConnection) new URL(url).openConnection();
      con.setRequestMethod(method);
      reader = new BufferedReader(new InputStreamReader(con.getInputStream()));
      StringBuilder sb = new StringBuilder();
      String line = null;
      while ((line = reader.readLine()) != null) {
        sb.append(line);
      }
      result = sb.toString();
    } catch (MalformedURLException e) {
      Log.e(TAG_NAME, e.getMessage(), e);
    } catch (IOException e) {
      Log.e(TAG_NAME, e.getMessage(), e);
    } finally {
      if (con != null) {
        con.disconnect();
      }
      try {
        if (reader != null) {
          reader.close();
        }
      } catch (IOException e) {
      }
    }
    Log.d(TAG_NAME, "response:" + result);
    return result;
  }

}

   
  








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.Get Url From Img Tag
11.Returns the contents of the given URL as an array of strings
12.Read from a URL
13.Pull the raw text content of the given URL.
14.Get Video from URL
15.Gets data 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