Android Tutorial - Network : Http Connection

Http Connection

    

import java.io.BufferedInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLEncoder;
import java.nio.ByteBuffer;
import java.nio.charset.Charset;
import java.util.ArrayList;
import java.util.Collection;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.util.zip.GZIPInputStream;

/**
 * Implementation of {@link Connection}.
 * 
 * @see org.jsoup.Jsoup#connect(String)
 */
public class HttpConnection implements Connection {
  public static Connection connect(String url) {
    Connection con = new HttpConnection();
    con.url(url);
    return con;
  }

  public static Connection connect(URL url) {
    Connection con = new HttpConnection();
    con.url(url);
    return con;
  }

  private Connection.Request req;
  private Connection.Response res;

  private HttpConnection() {
    req = new Request();
    res = new Response();
  }

  public Connection url(URL url) {
    req.url(url);
    return this;
  }

  public Connection url(String url) {
    Validate.notEmpty(url, "Must supply a valid URL");
    try {
      req.url(new URL(url));
    } catch (MalformedURLException e) {
      throw new IllegalArgumentException("Malformed URL: " + url, e);
    }
    return this;
  }

  public Connection userAgent(String userAgent) {
    Validate.notNull(userAgent, "User agent must not be null");
    req.header("User-Agent", userAgent);
    return this;
  }

  public Connection timeout(int millis) {
    req.timeout(millis);
    return this;
  }

  public Connection followRedirects(boolean followRedirects) {
    req.followRedirects(followRedirects);
    return this;
  }

  public Connection referrer(String referrer) {
    Validate.notNull(referrer, "Referrer must not be null");
    req.header("Referer", referrer);
    return this;
  }

  public Connection method(Method method) {
    req.method(method);
    return this;
  }

  public Connection data(String key, String value) {
    req.data(KeyVal.create(key, value));
    return this;
  }

  public Connection data(Map<String, String> data) {
    Validate.notNull(data, "Data map must not be null");
    for (Map.Entry<String, String> entry : data.entrySet()) {
      req.data(KeyVal.create(entry.getKey(), entry.getValue()));
    }
    return this;
  }

  public Connection data(String... keyvals) {
    Validate.notNull(keyvals, "Data key value pairs must not be null");
    Validate.isTrue(keyvals.length % 2 == 0,
        "Must supply an even number of key value pairs");
    for (int i = 0; i < keyvals.length; i += 2) {
      String key = keyvals[i];
      String value = keyvals[i + 1];
      Validate.notEmpty(key, "Data key must not be empty");
      Validate.notNull(value, "Data value must not be null");
      req.data(KeyVal.create(key, value));
    }
    return this;
  }

  public Connection header(String name, String value) {
    req.header(name, value);
    return this;
  }

  public Connection cookie(String name, String value) {
    req.cookie(name, value);
    return this;
  }

  public Connection.Response execute() throws IOException {
    res = Response.execute(req);
    return res;
  }

  public Connection.Request request() {
    return req;
  }

  public Connection request(Connection.Request request) {
    req = request;
    return this;
  }

  public Connection.Response response() {
    return res;
  }

  public Connection response(Connection.Response response) {
    res = response;
    return this;
  }

  @SuppressWarnings({ "unchecked" })
  private static abstract class Base<T extends Connection.Base> implements
      Connection.Base<T> {
    URL url;
    Method method;
    Map<String, String> headers;
    Map<String, String> cookies;

    private Base() {
      headers = new LinkedHashMap<String, String>();
      cookies = new LinkedHashMap<String, String>();
    }

    public URL url() {
      return url;
    }

    public T url(URL url) {
      Validate.notNull(url, "URL must not be null");
      this.url = url;
      return (T) this;
    }

    public Method method() {
      return method;
    }

    public T method(Method method) {
      Validate.notNull(method, "Method must not be null");
      this.method = method;
      return (T) this;
    }

    public String header(String name) {
      Validate.notNull(name, "Header name must not be null");
      return getHeaderCaseInsensitive(name);
    }

    public T header(String name, String value) {
      Validate.notEmpty(name, "Header name must not be empty");
      Validate.notNull(value, "Header value must not be null");
      removeHeader(name); // ensures we don't get an "accept-encoding" and
                // a "Accept-Encoding"
      headers.put(name, value);
      return (T) this;
    }

    public boolean hasHeader(String name) {
      Validate.notEmpty(name, "Header name must not be empty");
      return getHeaderCaseInsensitive(name) != null;
    }

    public T removeHeader(String name) {
      Validate.notEmpty(name, "Header name must not be empty");
      Map.Entry<String, String> entry = scanHeaders(name); // remove is
                                  // case
                                  // insensitive
                                  // too
      if (entry != null)
        headers.remove(entry.getKey()); // ensures correct case
      return (T) this;
    }

    public Map<String, String> headers() {
      return headers;
    }

    private String getHeaderCaseInsensitive(String name) {
      Validate.notNull(name, "Header name must not be null");
      // quick evals for common case of title case, lower case, then scan
      // for mixed
      String value = headers.get(name);
      if (value == null)
        value = headers.get(name.toLowerCase());
      if (value == null) {
        Map.Entry<String, String> entry = scanHeaders(name);
        if (entry != null)
          value = entry.getValue();
      }
      return value;
    }

    private Map.Entry<String, String> scanHeaders(String name) {
      String lc = name.toLowerCase();
      for (Map.Entry<String, String> entry : headers.entrySet()) {
        if (entry.getKey().toLowerCase().equals(lc))
          return entry;
      }
      return null;
    }

    public String cookie(String name) {
      Validate.notNull(name, "Cookie name must not be null");
      return cookies.get(name);
    }

    public T cookie(String name, String value) {
      Validate.notEmpty(name, "Cookie name must not be empty");
      Validate.notNull(value, "Cookie value must not be null");
      cookies.put(name, value);
      return (T) this;
    }

    public boolean hasCookie(String name) {
      Validate.notEmpty("Cookie name must not be empty");
      return cookies.containsKey(name);
    }

    public T removeCookie(String name) {
      Validate.notEmpty("Cookie name must not be empty");
      cookies.remove(name);
      return (T) this;
    }

    public Map<String, String> cookies() {
      return cookies;
    }
  }

  public static class Request extends Base<Connection.Request> implements
      Connection.Request {
    private int timeoutMilliseconds;
    private boolean followRedirects;
    private Collection<Connection.KeyVal> data;

    private Request() {
      timeoutMilliseconds = 3000;
      followRedirects = true;
      data = new ArrayList<Connection.KeyVal>();
      method = Connection.Method.GET;
      headers.put("Accept-Encoding", "gzip");
    }

    public int timeout() {
      return timeoutMilliseconds;
    }

    public Request timeout(int millis) {
      Validate.isTrue(millis >= 0,
          "Timeout milliseconds must be 0 (infinite) or greater");
      timeoutMilliseconds = millis;
      return this;
    }

    public boolean followRedirects() {
      return followRedirects;
    }

    public Connection.Request followRedirects(boolean followRedirects) {
      this.followRedirects = followRedirects;
      return this;
    }

    public Request data(Connection.KeyVal keyval) {
      Validate.notNull(keyval, "Key val must not be null");
      data.add(keyval);
      return this;
    }

    public Collection<Connection.KeyVal> data() {
      return data;
    }
  }

  public static class Response extends Base<Connection.Response> implements
      Connection.Response {
    private static final int MAX_REDIRECTS = 20;
    private int statusCode;
    private String statusMessage;
    private ByteBuffer byteData;
    private String charset;
    private String contentType;
    private boolean executed = false;
    private int numRedirects = 0;

    Response() {
      super();
    }

    private Response(Response previousResponse) throws IOException {
      super();
      if (previousResponse != null) {
        numRedirects = previousResponse.numRedirects + 1;
        if (numRedirects >= MAX_REDIRECTS)
          throw new IOException(
              String.format(
                  "Too many redirects occurred trying to load URL %s",
                  previousResponse.url()));
      }
    }

    static Response execute(Connection.Request req) throws IOException {
      return execute(req, null);
    }

    static Response execute(Connection.Request req,
        Response previousResponse) throws IOException {
      Validate.notNull(req, "Request must not be null");
      String protocol = req.url().getProtocol();
      Validate.isTrue(
          protocol.equals("http") || protocol.equals("https"),
          "Only http & https protocols supported");

      // set up the request for execution
      if (req.method() == Connection.Method.GET && req.data().size() > 0)
        serialiseRequestUrl(req); // appends query string
      HttpURLConnection conn = createConnection(req);
      conn.connect();
      if (req.method() == Connection.Method.POST)
        writePost(req.data(), conn.getOutputStream());

      int status = conn.getResponseCode();
      boolean needsRedirect = false;
      if (status != HttpURLConnection.HTTP_OK) {
        if (status == HttpURLConnection.HTTP_MOVED_TEMP
            || status == HttpURLConnection.HTTP_MOVED_PERM
            || status == HttpURLConnection.HTTP_SEE_OTHER)
          needsRedirect = true;
        else
          throw new IOException(status + " error loading URL "
              + req.url().toString());
      }
      Response res = new Response(previousResponse);
      res.setupFromConnection(conn, previousResponse);
      if (needsRedirect && req.followRedirects()) {
        req.url(new URL(req.url(), res.header("Location")));
        for (Map.Entry<String, String> cookie : res.cookies.entrySet()) { // add
                                          // response
                                          // cookies
                                          // to
                                          // request
                                          // (for
                                          // e.g.
                                          // login
                                          // posts)
          req.cookie(cookie.getKey(), cookie.getValue());
        }
        return execute(req, res);
      }

      InputStream inStream = null;
      try {
        inStream = res.hasHeader("Content-Encoding")
            && res.header("Content-Encoding").equalsIgnoreCase(
                "gzip") ? new BufferedInputStream(
            new GZIPInputStream(conn.getInputStream()))
            : new BufferedInputStream(conn.getInputStream());
        res.byteData = DataUtil.readToByteBuffer(inStream);
        res.charset = DataUtil
            .getCharsetFromContentType(res.contentType); // may be
                                    // null,
                                    // readInputStream
                                    // deals
                                    // with
                                    // it
      } finally {
        if (inStream != null)
          inStream.close();
      }

      res.executed = true;
      return res;
    }

    public int statusCode() {
      return statusCode;
    }

    public String statusMessage() {
      return statusMessage;
    }

    public String charset() {
      return charset;
    }

    public String contentType() {
      return contentType;
    }

    public String body() {
      Validate.isTrue(
          executed,
          "Request must be executed (with .execute(), .get(), or .post() before getting response body");
      // charset gets set from header on execute, and from meta-equiv on
      // parse. parse may not have happened yet
      String body;
      if (charset == null)
        body = Charset.forName(DataUtil.defaultCharset)
            .decode(byteData).toString();
      else
        body = Charset.forName(charset).decode(byteData).toString();
      byteData.rewind();
      return body;
    }

    public byte[] bodyAsBytes() {
      Validate.isTrue(
          executed,
          "Request must be executed (with .execute(), .get(), or .post() before getting response body");
      return byteData.array();
    }

    // set up connection defaults, and details from request
    private static HttpURLConnection createConnection(Connection.Request req)
        throws IOException {
      HttpURLConnection conn = (HttpURLConnection) req.url()
          .openConnection();
      conn.setRequestMethod(req.method().name());
      conn.setInstanceFollowRedirects(false); // don't rely on native
                          // redirection support
      conn.setConnectTimeout(req.timeout());
      conn.setReadTimeout(req.timeout());
      if (req.method() == Method.POST)
        conn.setDoOutput(true);
      if (req.cookies().size() > 0)
        conn.addRequestProperty("Cookie", getRequestCookieString(req));
      for (Map.Entry<String, String> header : req.headers().entrySet()) {
        conn.addRequestProperty(header.getKey(), header.getValue());
      }
      return conn;
    }

    // set up url, method, header, cookies
    private void setupFromConnection(HttpURLConnection conn,
        Connection.Response previousResponse) throws IOException {
      method = Connection.Method.valueOf(conn.getRequestMethod());
      url = conn.getURL();
      statusCode = conn.getResponseCode();
      statusMessage = conn.getResponseMessage();
      contentType = conn.getContentType();

      // headers into map
      Map<String, List<String>> resHeaders = conn.getHeaderFields();
      for (Map.Entry<String, List<String>> entry : resHeaders.entrySet()) {
        String name = entry.getKey();
        if (name == null)
          continue; // http/1.1 line

        List<String> values = entry.getValue();

        if (name.equalsIgnoreCase("Set-Cookie")) {
          for (String value : values) {
            TokenQueue cd = new TokenQueue(value);
            String cookieName = cd.chompTo("=").trim();
            String cookieVal = cd.consumeTo(";").trim();
            // ignores path, date, domain, secure et al. req'd?
            cookie(cookieName, cookieVal);
          }
        } else { // only take the first instance of each header
          if (!values.isEmpty())
            header(name, values.get(0));
        }
      }

      // if from a redirect, map previous response cookies into this
      // response
      if (previousResponse != null) {
        for (Map.Entry<String, String> prevCookie : previousResponse
            .cookies().entrySet()) {
          if (!hasCookie(prevCookie.getKey()))
            cookie(prevCookie.getKey(), prevCookie.getValue());
        }
      }
    }

    private static void writePost(Collection<Connection.KeyVal> data,
        OutputStream outputStream) throws IOException {
      OutputStreamWriter w = new OutputStreamWriter(outputStream,
          DataUtil.defaultCharset);
      boolean first = true;
      for (Connection.KeyVal keyVal : data) {
        if (!first)
          w.append('&');
        else
          first = false;

        w.write(URLEncoder.encode(keyVal.key(), DataUtil.defaultCharset));
        w.write('=');
        w.write(URLEncoder.encode(keyVal.value(),
            DataUtil.defaultCharset));
      }
      w.close();
    }

    private static String getRequestCookieString(Connection.Request req) {
      StringBuilder sb = new StringBuilder();
      boolean first = true;
      for (Map.Entry<String, String> cookie : req.cookies().entrySet()) {
        if (!first)
          sb.append("; ");
        else
          first = false;
        sb.append(cookie.getKey()).append('=')
            .append(cookie.getValue());
        // todo: spec says only ascii, no escaping / encoding defined.
        // validate on set? or escape somehow here?
      }
      return sb.toString();
    }

    // for get url reqs, serialise the data map into the url
    private static void serialiseRequestUrl(Connection.Request req)
        throws IOException {
      URL in = req.url();
      StringBuilder url = new StringBuilder();
      boolean first = true;
      // reconstitute the query, ready for appends
      url.append(in.getProtocol()).append("://")
          .append(in.getAuthority()) // includes host, port
          .append(in.getPath()).append("?");
      if (in.getQuery() != null) {
        url.append(in.getQuery());
        first = false;
      }
      for (Connection.KeyVal keyVal : req.data()) {
        if (!first)
          url.append('&');
        else
          first = false;
        url.append(
            URLEncoder.encode(keyVal.key(), DataUtil.defaultCharset))
            .append('=')
            .append(URLEncoder.encode(keyVal.value(),
                DataUtil.defaultCharset));
      }
      req.url(new URL(url.toString()));
      req.data().clear(); // moved into url as get params
    }
  }

  public static class KeyVal implements Connection.KeyVal {
    private String key;
    private String value;

    public static KeyVal create(String key, String value) {
      Validate.notEmpty(key, "Data key must not be empty");
      Validate.notNull(value, "Data value must not be null");
      return new KeyVal(key, value);
    }

    private KeyVal(String key, String value) {
      this.key = key;
      this.value = value;
    }

    public KeyVal key(String key) {
      Validate.notEmpty(key, "Data key must not be empty");
      this.key = key;
      return this;
    }

    public String key() {
      return key;
    }

    public KeyVal value(String value) {
      Validate.notNull(value, "Data value must not be null");
      this.value = value;
      return this;
    }

    public String value() {
      return value;
    }

    @Override
    public String toString() {
      return key + "=" + value;
    }
  }
}

/**
 * A Connection provides a convenient interface to fetch content from the web,
 * and parse them into Documents.
 * <p>
 * To get a new Connection, use {@link org.jsoup.Jsoup#connect(String)}.
 * Connections contain {@link Connection.Request} and
 * {@link Connection.Response} objects. The request objects are reusable as
 * prototype requests.
 * <p>
 * Request configuration can be made using either the shortcut methods in
 * Connection (e.g. {@link #userAgent(String)}), or by methods in the
 * Connection.Request object directly. All request configuration must be made
 * before the request is executed.
 * <p>
 * The Connection interface is <b>currently in beta</b> and subject to change.
 * Comments, suggestions, and bug reports are welcome.
 */
interface Connection {

  /**
   * GET and POST http methods.
   */
  public enum Method {
    GET, POST
  }

  /**
   * Set the request URL to fetch. The protocol must be HTTP or HTTPS.
   * 
   * @param url
   *            URL to connect to
   * @return this Connection, for chaining
   */
  public Connection url(URL url);

  /**
   * Set the request URL to fetch. The protocol must be HTTP or HTTPS.
   * 
   * @param url
   *            URL to connect to
   * @return this Connection, for chaining
   */
  public Connection url(String url);

  /**
   * Set the request user-agent header.
   * 
   * @param userAgent
   *            user-agent to use
   * @return this Connection, for chaining
   */
  public Connection userAgent(String userAgent);

  /**
   * Set the request timeouts (connect and read). If a timeout occurs, an
   * IOException will be thrown. The default timeout is 3 seconds (3000
   * millis). A timeout of zero is treated as an infinite timeout.
   * 
   * @param millis
   *            number of milliseconds (thousandths of a second) before timing
   *            out connects or reads.
   * @return this Connection, for chaining
   */
  public Connection timeout(int millis);

  /**
   * Set the request referrer (aka "referer") header.
   * 
   * @param referrer
   *            referrer to use
   * @return this Connection, for chaining
   */
  public Connection referrer(String referrer);

  /**
   * Configures the connection to (not) follow server redirects. By default
   * this is <b>true</b>.
   * 
   * @param followRedirects
   *            true if server redirects should be followed.
   * @return this Connection, for chaining
   */
  public Connection followRedirects(boolean followRedirects);

  /**
   * Set the request method to use, GET or POST. Default is GET.
   * 
   * @param method
   *            HTTP request method
   * @return this Connection, for chaining
   */
  public Connection method(Method method);

  /**
   * Add a request data parameter. Request parameters are sent in the request
   * query string for GETs, and in the request body for POSTs. A request may
   * have multiple values of the same name.
   * 
   * @param key
   *            data key
   * @param value
   *            data value
   * @return this Connection, for chaining
   */
  public Connection data(String key, String value);

  /**
   * Adds all of the supplied data to the request data parameters
   * 
   * @param data
   *            map of data parameters
   * @return this Connection, for chaining
   */
  public Connection data(Map<String, String> data);

  /**
   * Add a number of request data parameters. Multiple parameters may be set
   * at once, e.g.:
   * <code>.data("name", "jsoup", "language", "Java", "language", "English");</code>
   * creates a query string like:
   * <code>?name=jsoup&language=Java&language=English</code>
   * 
   * @param keyvals
   *            a set of key value pairs.
   * @return this Connection, for chaining
   */
  public Connection data(String... keyvals);

  /**
   * Set a request header.
   * 
   * @param name
   *            header name
   * @param value
   *            header value
   * @return this Connection, for chaining
   * @see org.jsoup.Connection.Request#headers()
   */
  public Connection header(String name, String value);

  /**
   * Set a cookie to be sent in the request
   * 
   * @param name
   *            name of cookie
   * @param value
   *            value of cookie
   * @return this Connection, for chaining
   */
  public Connection cookie(String name, String value);

  /**
   * Execute the request.
   * 
   * @return a response object
   * @throws IOException
   *             on error
   */
  public Response execute() throws IOException;

  /**
   * Get the request object associatated with this connection
   * 
   * @return request
   */
  public Request request();

  /**
   * Set the connection's request
   * 
   * @param request
   *            new request object
   * @return this Connection, for chaining
   */
  public Connection request(Request request);

  /**
   * Get the response, once the request has been executed
   * 
   * @return response
   */
  public Response response();

  /**
   * Set the conenction's response
   * 
   * @param response
   *            new response
   * @return this Connection, for chaining
   */
  public Connection response(Response response);

  /**
   * Common methods for Requests and Responses
   * 
   * @param <T>
   *            Type of Base, either Request or Response
   */
  interface Base<T extends Base> {

    /**
     * Get the URL
     * 
     * @return URL
     */
    public URL url();

    /**
     * Set the URL
     * 
     * @param url
     *            new URL
     * @return this, for chaining
     */
    public T url(URL url);

    /**
     * Get the request method
     * 
     * @return method
     */
    public Method method();

    /**
     * Set the request method
     * 
     * @param method
     *            new method
     * @return this, for chaining
     */
    public T method(Method method);

    /**
     * Get the value of a header. This is a simplified header model, where a
     * header may only have one value.
     * <p>
     * Header names are case insensitive.
     * 
     * @param name
     *            name of header (case insensitive)
     * @return value of header, or null if not set.
     * @see #hasHeader(String)
     * @see #cookie(String)
     */
    public String header(String name);

    /**
     * Set a header. This method will overwrite any existing header with the
     * same case insensitive name.
     * 
     * @param name
     *            Name of header
     * @param value
     *            Value of header
     * @return this, for chaining
     */
    public T header(String name, String value);

    /**
     * Check if a header is present
     * 
     * @param name
     *            name of header (case insensitive)
     * @return if the header is present in this request/response
     */
    public boolean hasHeader(String name);

    /**
     * Remove a header by name
     * 
     * @param name
     *            name of header to remove (case insensitive)
     * @return this, for chianing
     */
    public T removeHeader(String name);

    /**
     * Retrieve all of the request/response headers as a map
     * 
     * @return headers
     */
    public Map<String, String> headers();

    /**
     * Get a cookie value by name from this request/response.
     * <p>
     * Response objects have a simplified cookie model. Each cookie set in
     * the response is added to the response object's cookie key=value map.
     * The cookie's path, domain, and expiry date are ignored.
     * 
     * @param name
     *            name of cookie to retrieve.
     * @return value of cookie, or null if not set
     */
    public String cookie(String name);

    /**
     * Set a cookie in this request/response.
     * 
     * @param name
     *            name of cookie
     * @param value
     *            value of cookie
     * @return this, for chianing
     */
    public T cookie(String name, String value);

    /**
     * Check if a cookie is present
     * 
     * @param name
     *            name of cookie
     * @return if the cookie is present in this request/response
     */
    public boolean hasCookie(String name);

    /**
     * Remove a cookie by name
     * 
     * @param name
     *            name of cookie to remove
     * @return this, for chianing
     */
    public T removeCookie(String name);

    /**
     * Retrieve all of the request/response cookies as a map
     * 
     * @return cookies
     */
    public Map<String, String> cookies();

  }

  /**
   * Represents a HTTP request.
   */
  public interface Request extends Base<Request> {

    /**
     * Get the request timeout, in milliseconds.
     * 
     * @return the timeout in milliseconds.
     */
    public int timeout();

    /**
     * Update the request timeout.
     * 
     * @param millis
     *            timeout, in milliseconds
     * @return this Request, for chaining
     */
    public Request timeout(int millis);

    /**
     * Get the current followRedirects configuration.
     * 
     * @return true if followRedirects is enabled.
     */
    public boolean followRedirects();

    /**
     * Configures the request to (not) follow server redirects. By default
     * this is <b>true</b>.
     * 
     * @param followRedirects
     *            true if server redirects should be followed.
     * @return this Connection, for chaining
     */
    public Request followRedirects(boolean followRedirects);

    /**
     * Add a data parameter to the request
     * 
     * @param keyval
     *            data to add.
     * @return this Request, for chaining
     */
    public Request data(KeyVal keyval);

    /**
     * Get all of the request's data parameters
     * 
     * @return collection of keyvals
     */
    public Collection<KeyVal> data();

  }

  /**
   * Represents a HTTP response.
   */
  public interface Response extends Base<Response> {

    /**
     * Get the status code of the response.
     * 
     * @return status code
     */
    public int statusCode();

    /**
     * Get the status message of the response.
     * 
     * @return status message
     */
    public String statusMessage();

    /**
     * Get the character set name of the response.
     * 
     * @return character set name
     */
    public String charset();

    /**
     * Get the response content type (e.g. "text/html");
     * 
     * @return the response content type
     */
    public String contentType();

    /**
     * Get the body of the response as a plain string.
     * 
     * @return body
     */
    public String body();

    /**
     * Get the body of the response as an array of bytes.
     * 
     * @return body bytes
     */
    public byte[] bodyAsBytes();
  }

  /**
   * A Key Value tuple.
   */
  public interface KeyVal {

    /**
     * Update the key of a keyval
     * 
     * @param key
     *            new key
     * @return this KeyVal, for chaining
     */
    public KeyVal key(String key);

    /**
     * Get the key of a keyval
     * 
     * @return the key
     */
    public String key();

    /**
     * Update the value of a keyval
     * 
     * @param value
     *            the new value
     * @return this KeyVal, for chaining
     */
    public KeyVal value(String value);

    /**
     * Get the value of a keyval
     * 
     * @return the value
     */
    public String value();
  }
}

final class Validate {

  private Validate() {
  }

  /**
   * Validates that the obect is not null
   * 
   * @param obj
   *            object to test
   */
  public static void notNull(Object obj) {
    if (obj == null)
      throw new IllegalArgumentException("Object must not be null");
  }

  /**
   * Validates that the object is not null
   * 
   * @param obj
   *            object to test
   * @param msg
   *            message to output if validation fails
   */
  public static void notNull(Object obj, String msg) {
    if (obj == null)
      throw new IllegalArgumentException(msg);
  }

  /**
   * Validates that the value is true
   * 
   * @param val
   *            object to test
   */
  public static void isTrue(boolean val) {
    if (!val)
      throw new IllegalArgumentException("Must be true");
  }

  /**
   * Validates that the value is true
   * 
   * @param val
   *            object to test
   * @param msg
   *            message to output if validation fails
   */
  public static void isTrue(boolean val, String msg) {
    if (!val)
      throw new IllegalArgumentException(msg);
  }

  /**
   * Validates that the array contains no null elements
   * 
   * @param objects
   *            the array to test
   */
  public static void noNullElements(Object[] objects) {
    noNullElements(objects, "Array must not contain any null objects");
  }

  /**
   * Validates that the array contains no null elements
   * 
   * @param objects
   *            the array to test
   * @param msg
   *            message to output if validation fails
   */
  public static void noNullElements(Object[] objects, String msg) {
    for (Object obj : objects)
      if (obj == null)
        throw new IllegalArgumentException(msg);
  }

  /**
   * Validates that the string is not empty
   * 
   * @param string
   *            the string to test
   */
  public static void notEmpty(String string) {
    if (string == null || string.length() == 0)
      throw new IllegalArgumentException("String must not be empty");
  }

  /**
   * Validates that the string is not empty
   * 
   * @param string
   *            the string to test
   * @param msg
   *            message to output if validation fails
   */
  public static void notEmpty(String string, String msg) {
    if (string == null || string.length() == 0)
      throw new IllegalArgumentException(msg);
  }
}

/**
 * Internal static utilities for handling data.
 * 
 */
class DataUtil {
  private static final Pattern charsetPattern = Pattern
      .compile("(?i)\\bcharset=\\s*\"?([^\\s;\"]*)");
  static final String defaultCharset = "UTF-8"; // used if not found in header
                          // or meta charset
  private static final int bufferSize = 0x20000; // ~130K.

  private DataUtil() {
  }

  /**
   * Loads a file to a Document.
   * 
   * @param in
   *            file to load
   * @param charsetName
   *            character set of input
   * @param baseUri
   *            base URI of document, to resolve relative links against
   * @return Document
   * @throws IOException
   *             on IO error
   */

  static ByteBuffer readToByteBuffer(InputStream inStream) throws IOException {
    byte[] buffer = new byte[bufferSize];
    ByteArrayOutputStream outStream = new ByteArrayOutputStream(bufferSize);
    int read;
    while (true) {
      read = inStream.read(buffer);
      if (read == -1)
        break;
      outStream.write(buffer, 0, read);
    }
    ByteBuffer byteData = ByteBuffer.wrap(outStream.toByteArray());
    return byteData;
  }

  /**
   * Parse out a charset from a content type header.
   * 
   * @param contentType
   *            e.g. "text/html; charset=EUC-JP"
   * @return "EUC-JP", or null if not found. Charset is trimmed and
   *         uppercased.
   */
  static String getCharsetFromContentType(String contentType) {
    if (contentType == null)
      return null;

    Matcher m = charsetPattern.matcher(contentType);
    if (m.find()) {
      return m.group(1).trim().toUpperCase();
    }
    return null;
  }

}

/**
 * A character queue with parsing helpers.
 *
 * @author Jonathan Hedley
 */
class TokenQueue {
    private String queue;
    private int pos = 0;
    
    private static final char ESC = '\\'; // escape char for chomp balanced.

    /**
     Create a new TokenQueue.
     @param data string of data to back queue.
     */
    public TokenQueue(String data) {
        Validate.notNull(data);
        queue = data;
    }

    /**
     * Is the queue empty?
     * @return true if no data left in queue.
     */
    public boolean isEmpty() {
        return remainingLength() == 0;
    }
    
    private int remainingLength() {
        return queue.length() - pos;
    }

    /**
     * Retrieves but does not remove the first character from the queue.
     * @return First character, or 0 if empty.
     */
    public char peek() {
        return isEmpty() ? 0 : queue.charAt(pos);
    }

    /**
     Add a character to the start of the queue (will be the next character retrieved).
     @param c character to add
     */
    public void addFirst(Character c) {
        addFirst(c.toString());
    }

    /**
     Add a string to the start of the queue.
     @param seq string to add.
     */
    public void addFirst(String seq) {
        // not very performant, but an edge case
        queue = seq + queue.substring(pos);
        pos = 0;
    }

    /**
     * Tests if the next characters on the queue match the sequence. Case insensitive.
     * @param seq String to check queue for.
     * @return true if the next characters match.
     */
    public boolean matches(String seq) {
        return queue.regionMatches(true, pos, seq, 0, seq.length());
    }

    /**
     * Case sensitive match test.
     * @param seq
     * @return
     */
    public boolean matchesCS(String seq) {
        return queue.startsWith(seq, pos);
    }
    

    /**
     Tests if the next characters match any of the sequences. Case insensitive.
     @param seq
     @return
     */
    public boolean matchesAny(String... seq) {
        for (String s : seq) {
            if (matches(s))
                return true;
        }
        return false;
    }

    public boolean matchesAny(char... seq) {
        if (isEmpty())
            return false;

        for (char c: seq) {
            if (queue.charAt(pos) == c)
                return true;
        }
        return false;
    }

    public boolean matchesStartTag() {
        // micro opt for matching "<x"
        return (remainingLength() >= 2 && queue.charAt(pos) == '<' && Character.isLetter(queue.charAt(pos+1)));
    }

    /**
     * Tests if the queue matches the sequence (as with match), and if they do, removes the matched string from the
     * queue.
     * @param seq String to search for, and if found, remove from queue.
     * @return true if found and removed, false if not found.
     */
    public boolean matchChomp(String seq) {
        if (matches(seq)) {
            pos += seq.length();
            return true;
        } else {
            return false;
        }
    }

    /**
     Tests if queue starts with a whitespace character.
     @return if starts with whitespace
     */
    public boolean matchesWhitespace() {
        return !isEmpty() && Character.isWhitespace(queue.charAt(pos));
    }

    /**
     Test if the queue matches a word character (letter or digit).
     @return if matches a word character
     */
    public boolean matchesWord() {
        return !isEmpty() && Character.isLetterOrDigit(queue.charAt(pos));
    }

    /**
     * Drops the next character off the queue.
     */
    public void advance() {
        if (!isEmpty()) pos++;
    }

    /**
     * Consume one character off queue.
     * @return first character on queue.
     */
    public char consume() {
        return queue.charAt(pos++);
    }

    /**
     * Consumes the supplied sequence of the queue. If the queue does not start with the supplied sequence, will
     * throw an illegal state exception -- but you should be running match() against that condition.
     <p>
     Case insensitive.
     * @param seq sequence to remove from head of queue.
     */
    public void consume(String seq) {
        if (!matches(seq))
            throw new IllegalStateException("Queue did not match expected sequence");
        int len = seq.length();
        if (len > remainingLength())
            throw new IllegalStateException("Queue not long enough to consume sequence");
        
        pos += len;
    }

    /**
     * Pulls a string off the queue, up to but exclusive of the match sequence, or to the queue running out.
     * @param seq String to end on (and not include in return, but leave on queue). <b>Case sensitive.</b>
     * @return The matched data consumed from queue.
     */
    public String consumeTo(String seq) {
        int offset = queue.indexOf(seq, pos);
        if (offset != -1) {
            String consumed = queue.substring(pos, offset);
            pos += consumed.length();
            return consumed;
        } else {
            return remainder();
        }
    }
    
    public String consumeToIgnoreCase(String seq) {
        int start = pos;
        String first = seq.substring(0, 1);
        boolean canScan = first.toLowerCase().equals(first.toUpperCase()); // if first is not cased, use index of
        while (!isEmpty()) {
            if (matches(seq))
                break;
            
            if (canScan) {
                int skip = queue.indexOf(first, pos) - pos;
                if (skip == 0) // this char is the skip char, but not match, so force advance of pos
                    pos++;
                else if (skip < 0) // no chance of finding, grab to end
                    pos = queue.length();
                else
                    pos += skip;
            }
            else
                pos++;
        }

        String data = queue.substring(start, pos); 
        return data; 
    }

    /**
     Consumes to the first sequence provided, or to the end of the queue. Leaves the terminator on the queue.
     @param seq any number of terminators to consume to. <b>Case insensitive.</b>
     @return consumed string   
     */
    // todo: method name. not good that consumeTo cares for case, and consume to any doesn't. And the only use for this
    // is is a case sensitive time...
    public String consumeToAny(String... seq) {
        int start = pos;
        while (!isEmpty() && !matchesAny(seq)) {
            pos++;
        }

        String data = queue.substring(start, pos); 
        return data; 
    }

    /**
     * Pulls a string off the queue (like consumeTo), and then pulls off the matched string (but does not return it).
     * <p>
     * If the queue runs out of characters before finding the seq, will return as much as it can (and queue will go
     * isEmpty() == true).
     * @param seq String to match up to, and not include in return, and to pull off queue. <b>Case sensitive.</b>
     * @return Data matched from queue.
     */
    public String chompTo(String seq) {
        String data = consumeTo(seq);
        matchChomp(seq);
        return data;
    }
    
    public String chompToIgnoreCase(String seq) {
        String data = consumeToIgnoreCase(seq); // case insensitive scan
        matchChomp(seq);
        return data;
    }

    /**
     * Pulls a balanced string off the queue. E.g. if queue is "(one (two) three) four", (,) will return "one (two) three",
     * and leave " four" on the queue. Unbalanced openers and closers can be escaped (with \). Those escapes will be left
     * in the returned string, which is suitable for regexes (where we need to preserve the escape), but unsuitable for
     * contains text strings; use unescape for that.
     * @param open opener
     * @param close closer
     * @return data matched from the queue
     */
    public String chompBalanced(char open, char close) {
        StringBuilder accum = new StringBuilder();
        int depth = 0;
        char last = 0;

        do {
            if (isEmpty()) break;
            Character c = consume();
            if (last == 0 || last != ESC) {
                if (c.equals(open))
                    depth++;
                else if (c.equals(close))
                    depth--;
            }

            if (depth > 0 && last != 0)
                accum.append(c); // don't include the outer match pair in the return
            last = c;
        } while (depth > 0);
        return accum.toString();
    }
    
    /**
     * Unescaped a \ escaped string.
     * @param in backslash escaped string
     * @return unescaped string
     */
    public static String unescape(String in) {
        StringBuilder out = new StringBuilder();
        char last = 0;
        for (char c : in.toCharArray()) {
            if (c == ESC) {
                if (last != 0 && last == ESC)
                    out.append(c);
            }
            else 
                out.append(c);
            last = c;
        }
        return out.toString();
    }

    /**
     * Pulls the next run of whitespace characters of the queue.
     */
    public boolean consumeWhitespace() {
        boolean seen = false;
        while (matchesWhitespace()) {
            pos++;
            seen = true;
        }
        return seen;
    }

    /**
     * Retrieves the next run of word type (letter or digit) off the queue.
     * @return String of word characters from queue, or empty string if none.
     */
    public String consumeWord() {
        int start = pos;
        while (matchesWord())
            pos++;
        return queue.substring(start, pos);
    }
    
    /**
     * Consume an tag name off the queue (word or :, _, -)
     * 
     * @return tag name
     */
    public String consumeTagName() {
        int start = pos;
        while (!isEmpty() && (matchesWord() || matchesAny(':', '_', '-')))
            pos++;
        
        return queue.substring(start, pos);
    }
    
    /**
     * Consume a CSS element selector (tag name, but | instead of : for namespaces, to not conflict with :pseudo selects).
     * 
     * @return tag name
     */
    public String consumeElementSelector() {
        int start = pos;
        while (!isEmpty() && (matchesWord() || matchesAny('|', '_', '-')))
            pos++;
        
        return queue.substring(start, pos);
    }

    /**
     Consume a CSS identifier (ID or class) off the queue (letter, digit, -, _)
     http://www.w3.org/TR/CSS2/syndata.html#value-def-identifier
     @return identifier
     */
    public String consumeCssIdentifier() {
        int start = pos;
        while (!isEmpty() && (matchesWord() || matchesAny('-', '_')))
            pos++;

        return queue.substring(start, pos);
    }

    /**
     Consume an attribute key off the queue (letter, digit, -, _, :")
     @return attribute key
     */
    public String consumeAttributeKey() {
        int start = pos;
        while (!isEmpty() && (matchesWord() || matchesAny('-', '_', ':')))
            pos++;
        
        return queue.substring(start, pos);
    }

    /**
     Consume and return whatever is left on the queue.
     @return remained of queue.
     */
    public String remainder() {
        StringBuilder accum = new StringBuilder();
        while (!isEmpty()) {
            accum.append(consume());
        }
        return accum.toString();
    }
    
    public String toString() {
        return queue.substring(pos);
    }
}
 

Using HttpGet to get the web response

package com.commonsware.android.internet;

import android.app.Activity;
import android.content.Context;
import android.location.Criteria;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Bundle;
import android.webkit.WebView;
import android.widget.Toast;
import java.io.StringReader;
import java.util.ArrayList;
import java.util.List;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import org.apache.http.client.ResponseHandler;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.BasicResponseHandler;
import org.apache.http.impl.client.DefaultHttpClient;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.NodeList;
import org.xml.sax.InputSource;

public class WeatherDemo extends Activity {
  private LocationManager mgr=null;
  private String format;
  private WebView browser;
  private HttpClient client;
  private List<Forecast> forecasts=new ArrayList<Forecast>();
  
  @Override
  public void onCreate(Bundle icicle) {
    super.onCreate(icicle);
    setContentView(R.layout.main);
    
    mgr=(LocationManager)getSystemService(Context.LOCATION_SERVICE);
    format=getString(R.string.url);
    browser=(WebView)findViewById(R.id.webkit);
    client=new DefaultHttpClient();
  }
  
  @Override
  public void onResume() {
    super.onResume();
    
    mgr.requestLocationUpdates(LocationManager.GPS_PROVIDER,
                                0, 10000.0f,
                                onLocationChange);
  }
  
  @Override
  public void onPause() {
    super.onPause();
    
    mgr.removeUpdates(onLocationChange);
  }
  
  private void updateForecast(Location loc) {
    String url=String.format(format, loc.getLatitude(),
                             loc.getLongitude());
    HttpGet getMethod=new HttpGet(url);
    
    try {
      ResponseHandler<String> responseHandler=new BasicResponseHandler();
      String responseBody=client.execute(getMethod,
                                         responseHandler);
      buildForecasts(responseBody);
      
      String page=generatePage();
    
      browser.loadDataWithBaseURL(null, page, "text/html",
                                  "UTF-8", null);
    }
    catch (Throwable t) {
      android.util.Log.e("WeatherDemo", "Exception fetching data", t);
      Toast
        .makeText(this, "Request failed: "+t.toString(), 4000)
        .show();
    }
  }
  
  void buildForecasts(String raw) throws Exception {
    DocumentBuilder builder=DocumentBuilderFactory
                              .newInstance()
                              .newDocumentBuilder();
    Document doc=builder.parse(new InputSource(new StringReader(raw)));
    NodeList times=doc.getElementsByTagName("start-valid-time");
    
    for (int i=0;i<times.getLength();i++) {
      Element time=(Element)times.item(i);
      Forecast forecast=new Forecast();
      
      forecasts.add(forecast);
      forecast.setTime(time.getFirstChild().getNodeValue());
    }
    
    NodeList temps=doc.getElementsByTagName("value");
    
    for (int i=0;i<temps.getLength();i++) {
      Element temp=(Element)temps.item(i);
      Forecast forecast=forecasts.get(i);
      
      forecast.setTemp(new Integer(temp.getFirstChild().getNodeValue()));
    }
    
    NodeList icons=doc.getElementsByTagName("icon-link");
    
    for (int i=0;i<icons.getLength();i++) {
      Element icon=(Element)icons.item(i);
      Forecast forecast=forecasts.get(i);
      
      forecast.setIcon(icon.getFirstChild().getNodeValue());
    }
  }
  
  String generatePage() {
    StringBuilder bufResult=new StringBuilder("<html><body><table>");
    
    bufResult.append("<tr><th width=\"50%\">Time</th>"+
                      "<th>Temperature</th><th>Forecast</th></tr>");
    
    for (Forecast forecast : forecasts) {
      bufResult.append("<tr><td align=\"center\">");
      bufResult.append(forecast.getTime());
      bufResult.append("</td><td align=\"center\">");
      bufResult.append(forecast.getTemp());
      bufResult.append("</td><td><img src=\"");
      bufResult.append(forecast.getIcon());
      bufResult.append("\"></td></tr>");
    }
    
    bufResult.append("</table></body></html>");
    
    return(bufResult.toString());
  }
  
  LocationListener onLocationChange=new LocationListener() {
    public void onLocationChanged(Location location) {
      updateForecast(location);
    }
    
    public void onProviderDisabled(String provider) {
      // required for interface, not used
    }
    
    public void onProviderEnabled(String provider) {
      // required for interface, not used
    }
    
    public void onStatusChanged(String provider, int status,
                                  Bundle extras) {
      // required for interface, not used
    }
  };
  
  class Forecast {
    String time="";
    Integer temp=null;
    String iconUrl="";
    
    String getTime() {
      return(time);
    }
  
    void setTime(String time) {
      this.time=time.substring(0,16).replace('T', ' ');
    }
    
    Integer getTemp() {
      return(temp);
    }
    
    void setTemp(Integer temp) {
      this.temp=temp;
    }
    
    String getIcon() {
      return(iconUrl);
    }
    
    void setIcon(String iconUrl) {
      this.iconUrl=iconUrl;
    }
  }
}

//res\layout\main.xml
<?xml version="1.0" encoding="utf-8"?>
<WebView xmlns:android="http://schemas.android.com/apk/res/android"
  android:id="@+id/webkit"
  android:layout_width="fill_parent"
  android:layout_height="fill_parent" 

  />

Create Http connection

    

package app.test;

import java.io.IOException;

import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.conn.ClientConnectionManager;
import org.apache.http.conn.scheme.SchemeRegistry;
import org.apache.http.impl.client.BasicResponseHandler;
import org.apache.http.params.BasicHttpParams;
import org.apache.http.params.HttpConnectionParams;
import org.apache.http.params.HttpParams;

import android.app.Activity;
import android.app.Application;
import android.net.http.AndroidHttpClient;
import android.os.Bundle;
import android.util.Log;

class ApplicationEx extends Application {
  String TAG = "ApplicationEx";
  private AndroidHttpClient httpClient;

  @Override
  public void onCreate() {
    super.onCreate();
    httpClient = createHttpClient();
  }

  private AndroidHttpClient createHttpClient() {
    AndroidHttpClient httpClient = AndroidHttpClient.newInstance("Mozilla/5.0 (Linux; U; Android 2.1; en-us; ADR6200 Build/ERD79) AppleWebKit/530.17 (KHTML, like Gecko) Version/ 4.0 Mobile Safari/530.17");

    ClientConnectionManager conMgr = httpClient.getConnectionManager();
    SchemeRegistry schReg = conMgr.getSchemeRegistry();
    for (String scheme : schReg.getSchemeNames()) {
      Log.v(TAG,"Scheme: "+ scheme+ ", port: "
              + schReg.getScheme(scheme).getDefaultPort()
              + ", factory: "
              + schReg.getScheme(scheme).getSocketFactory()
                  .getClass().getName());
    }

    HttpParams params = httpClient.getParams();
    Log.v(TAG,"http.protocol.version: "+ params.getParameter("http.protocol.version"));
    Log.v(TAG,"http.protocol.content-charset: "+ params.getParameter("http.protocol.content-charset"));
    Log.v(TAG,"http.protocol.handle-redirects: "+ params.getParameter("http.protocol.handle-redirects"));
    Log.v(TAG,"http.conn-manager.timeout: "+ params.getParameter("http.conn-manager.timeout"));
    Log.v(TAG,"http.socket.timeout: "+ params.getParameter("http.socket.timeout"));
    Log.v(TAG,"http.connection.timeout: "+ params.getParameter("http.connection.timeout"));
    return httpClient;
  }

  public AndroidHttpClient getHttpClient() {
    if (httpClient == null)
      httpClient = createHttpClient();
    return httpClient;
  }

  @Override
  public void onLowMemory() {
    super.onLowMemory();
    shutdownHttpClient();
  }

  @Override
  public void onTerminate() {
    super.onTerminate();
    shutdownHttpClient();
  }

  private void shutdownHttpClient() {
    if (httpClient != null) {
      if (httpClient.getConnectionManager() != null) {
        httpClient.getConnectionManager().shutdown();
      }
      httpClient.close();
      httpClient = null;
    }
  }
}

public class Test extends Activity {
  private ApplicationEx app;
  private HttpClient httpClient;

  @Override
  public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    app = (ApplicationEx) this.getApplication();
    httpClient = app.getHttpClient();
    getHttpContent();
  }

  public void getHttpContent() {
    try {
      HttpGet request = new HttpGet("http://www.google.com/");
      HttpParams params = new BasicHttpParams();
      HttpConnectionParams.setSoTimeout(params, 60000); // 1 minute
      request.setParams(params);
      Log.v("connection timeout", String.valueOf(HttpConnectionParams
          .getConnectionTimeout(params)));
      Log.v("socket timeout",
          String.valueOf(HttpConnectionParams.getSoTimeout(params)));

      String page = httpClient.execute(request,
          new BasicResponseHandler());
      System.out.println(page);
    } catch (IOException e) {
      // covers:
      // ClientProtocolException
      // ConnectTimeoutException
      // ConnectionPoolTimeoutException
      // SocketTimeoutException
      e.printStackTrace();
    }
  }
} 

Http connection with

    

package app.test;
import org.apache.http.HttpVersion;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.conn.ClientConnectionManager;
import org.apache.http.conn.params.ConnManagerParams;
import org.apache.http.conn.scheme.PlainSocketFactory;
import org.apache.http.conn.scheme.Scheme;
import org.apache.http.conn.scheme.SchemeRegistry;
import org.apache.http.conn.ssl.SSLSocketFactory;
import org.apache.http.impl.client.BasicResponseHandler;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.impl.conn.tsccm.ThreadSafeClientConnManager;
import org.apache.http.params.BasicHttpParams;
import org.apache.http.params.HttpConnectionParams;
import org.apache.http.params.HttpParams;
import org.apache.http.params.HttpProtocolParams;
import org.apache.http.protocol.HTTP;

import android.app.Activity;
import android.os.Bundle;
import android.util.Log;

class CustomHttpClient {
  private static HttpClient customHttpClient;
  public static synchronized HttpClient getHttpClient() {
    if (customHttpClient != null) {
      return customHttpClient;
    }
        HttpParams params = new BasicHttpParams();
        HttpProtocolParams.setVersion(params, HttpVersion.HTTP_1_1);
        HttpProtocolParams.setContentCharset(params, HTTP.DEFAULT_CONTENT_CHARSET);
        HttpProtocolParams.setUseExpectContinue(params, true);
        HttpProtocolParams.setUserAgent(params,"Mozilla/5.0 (Linux; U; Android 2.2.1;");
        ConnManagerParams.setTimeout(params, 1000);
        HttpConnectionParams.setConnectionTimeout(params, 5000);
        HttpConnectionParams.setSoTimeout(params, 10000);

        SchemeRegistry schReg = new SchemeRegistry();
        schReg.register(new Scheme("http", PlainSocketFactory.getSocketFactory(), 80));
        schReg.register(new Scheme("https",SSLSocketFactory.getSocketFactory(), 443));
        ClientConnectionManager conMgr = new ThreadSafeClientConnManager(params,schReg);
        customHttpClient = new DefaultHttpClient(conMgr, params);
    return customHttpClient;
  }
  public Object clone() throws CloneNotSupportedException {
    throw new CloneNotSupportedException();
  }
}
public class Test extends Activity{
    private HttpClient httpClient;
    @Override
    public void onCreate(Bundle savedInstanceState){
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        httpClient = CustomHttpClient.getHttpClient();
        getHttpContent();
    }
    public void getHttpContent(){
        try {
            HttpGet request = new HttpGet("http://www.google.com/");
            HttpParams params = request.getParams();
            HttpConnectionParams.setSoTimeout(params, 60000);   // 1 minute
            request.setParams(params);
            Log.v("connection timeout", String.valueOf(HttpConnectionParams.getConnectionTimeout(params)));
            Log.v("socket timeout", String.valueOf(HttpConnectionParams.getSoTimeout(params)));

            String page = httpClient.execute(request, new BasicResponseHandler());
            System.out.println(page);
    } catch (Exception e) {
      e.printStackTrace();
    }
    }
} 

Http Get and DefaultHttpClient

    

//package com.joke.praser;

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

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

public class HttpUtils {

  private static final String tag = "HttpUtils";

  private static final int DEFAULT_BUFFER_SIZE = 8192;

  /**
   * ????
   * 
   * @param url
   * @return
   */
  public static String httpGet(String url) {

    DefaultHttpClient httpclient = new DefaultHttpClient();
    try {
      HttpGet httpget = new HttpGet(url);
      httpget.addHeader("User-Agent", "ie 6");
      HttpResponse response = httpclient.execute(httpget);
      HttpEntity entity = response.getEntity();
      return generateString(entity.getContent());
    } catch (IOException e) {
      e.printStackTrace();
      return null;
    }

  }
  
  /**
   * ????
   * 
   * @param url
   * @return
   */
  public static InputStream httpGetIS(String url) {

    DefaultHttpClient httpclient = new DefaultHttpClient();
    try {
      HttpGet httpget = new HttpGet(url);
      httpget.addHeader("User-Agent", "ie 6");
      HttpResponse response = httpclient.execute(httpget);
      HttpEntity entity = response.getEntity();
      return entity.getContent();
    } catch (IOException e) {
      e.printStackTrace();
      return null;
    }

  }

  private static String generateString(InputStream stream) {
    StringBuilder sb = new StringBuilder();
    InputStreamReader reader = null;
    try {
      reader = new InputStreamReader(stream, "utf-8");
      BufferedReader buffer = new BufferedReader(reader);
      String cur;
      while ((cur = buffer.readLine()) != null) {
        sb.append(cur + "\n");
      }

    } catch (UnsupportedEncodingException e1) {
      e1.printStackTrace();
      return null;
    } catch (IOException e) {
      e.printStackTrace();
      return null;
    } finally {
      if (reader != null) {
        try {
          reader.close();
          reader = null;
        } catch (IOException e) {
          e.printStackTrace();
        }
      }
      if (stream != null) {
        try {
          stream.close();
          stream = null;
        } catch (IOException e) {
          e.printStackTrace();
        }
      }
    }

    return sb.toString();
  }
 

}

Http Post

    

package app.test;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.List;

import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;

import android.app.Activity;
import android.os.Bundle;

public class Test extends Activity {
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        BufferedReader in = null;
        try {
            HttpClient client = new DefaultHttpClient();
            HttpPost request = new HttpPost("http://yourService.com/doSomething.do");
            List<NameValuePair> postParameters = new ArrayList<NameValuePair>();
            postParameters.add(new BasicNameValuePair("first", "param value one"));
            postParameters.add(new BasicNameValuePair("issuenum", "10317"));
            postParameters.add(new BasicNameValuePair("username", "dave"));
            UrlEncodedFormEntity formEntity = new UrlEncodedFormEntity(
                    postParameters);

            request.setEntity(formEntity);
            HttpResponse response = client.execute(request);
            in = new BufferedReader(new InputStreamReader(response.getEntity().getContent()));
            StringBuffer sb = new StringBuffer("");
            String line = "";
            String NL = System.getProperty("line.separator");
            while ((line = in.readLine()) != null) {
                sb.append(line + NL);
            }
            in.close();
            String result = sb.toString();
            System.out.println(result);
        } catch(Exception e) {
        }
    }
} 

Simple HTTP Request

    
package app.test;

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

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

import android.app.Activity;
import android.os.Bundle;
import android.util.Log;

public class Test extends Activity {

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);

        HttpClient httpclient = new DefaultHttpClient();
        HttpGet httpget = new HttpGet("http://java2s.com");

        try {
            HttpResponse response = httpclient.execute(httpget);
            HttpEntity entity = response.getEntity();

            if (entity != null) {
                InputStream inputstream = entity.getContent();
                BufferedReader bufferedreader =
                  new BufferedReader(new InputStreamReader(inputstream));
                StringBuilder stringbuilder = new StringBuilder();

                String currentline = null;
                while ((currentline = bufferedreader.readLine()) != null) {
                    stringbuilder.append(currentline + "\n");
                }
                String result = stringbuilder.toString();
                Log.v("HTTP REQUEST",result);
                inputstream.close();
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    } 

}

Http Request Class

    
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.net.URL;
import java.net.URLConnection;
import java.net.URLEncoder;
import java.util.Enumeration;
import java.util.Hashtable;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;

import android.util.Log;

class HttpData {
  public String content;
  public Hashtable cookies = new Hashtable();
  public Hashtable headers = new Hashtable();
}

public class HttpRequest {


  public static HttpData get(String sUrl) throws Exception {
    HttpData ret = null;
    String str;
    StringBuffer buff = new StringBuffer();
    // try {
    URL url = new URL(sUrl);
    URLConnection con = url.openConnection();

    BufferedReader in = new BufferedReader(new

    InputStreamReader(con.getInputStream()));

    while ((str = in.readLine()) != null) {
      buff.append(str);
    }

    ret = new HttpData();
    ret.content = buff.toString();
    // get headers
    Map<String, List<String>> headers = con.getHeaderFields();
    Set<Entry<String, List<String>>> hKeys = headers.entrySet();
    for (Iterator<Entry<String, List<String>>> i = hKeys.iterator(); i
        .hasNext();) {
      Entry<String, List<String>> m = i.next();

      ret.headers.put(m.getKey(), m.getValue().toString());
      if (m.getKey().equals("set-cookie"))
        ret.cookies.put(m.getKey(), m.getValue().toString());
    }

    return ret;
  }

  public static HttpData post(String sUrl, Hashtable<String, String> ht)
      throws Exception {
    String key;
    StringBuffer data = new StringBuffer();
    Enumeration<String> keys = ht.keys();
    while (keys.hasMoreElements()) {
      key = keys.nextElement();
      data.append(URLEncoder.encode(key, "UTF-8"));
      data.append("=");
      data.append(URLEncoder.encode(ht.get(key), "UTF-8"));
      data.append("&amp;");
    }
    return HttpRequest.post(sUrl, data.toString());
  }

  public static HttpData post(String sUrl, String data) {
    StringBuffer ret = new StringBuffer();
    HttpData dat = new HttpData();
    String header;
    try {
      // Send data
      URL url = new URL(sUrl);
      URLConnection conn = url.openConnection();
      conn.setDoOutput(true);
      OutputStreamWriter wr = new OutputStreamWriter(
          conn.getOutputStream());
      wr.write(data);
      wr.flush();

      // Get the response

      Map<String, List<String>> headers = conn.getHeaderFields();
      Set<Entry<String, List<String>>> hKeys = headers.entrySet();
      for (Iterator<Entry<String, List<String>>> i = hKeys.iterator(); i
          .hasNext();) {
        Entry<String, List<String>> m = i.next();

        dat.headers.put(m.getKey(), m.getValue().toString());
        if (m.getKey().equals("set-cookie"))
          dat.cookies.put(m.getKey(), m.getValue().toString());
      }
      BufferedReader rd = new BufferedReader(new

      InputStreamReader(conn.getInputStream()));
      String line;
      while ((line = rd.readLine()) != null) {
        ret.append(line);
      }
      Log.e("ERROR", line);
      wr.close();
      rd.close();
    } catch (Exception e) {
      e.printStackTrace();
      Log.e("ERROR", "ERROR IN CODE:" + e.getMessage());
    }
    dat.content = ret.toString();
    return dat;
  }
 

} 

Http Get and Http Post

    
//package com.helloandroid.acashboard.utils;

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.auth.AuthScope;
import org.apache.http.auth.UsernamePasswordCredentials;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicHttpResponse;
import org.apache.http.protocol.HTTP;

import android.content.Context;
import android.content.SharedPreferences;
import android.preference.PreferenceManager;

public class ApiHelper {

  SharedPreferences preferences;
  static String username;
  static String apiKey;

  public ApiHelper(Context context) {
    preferences = PreferenceManager.getDefaultSharedPreferences(context);
    username = preferences.getString("editTextName", "helloandroid"); // ezek
                                      // valtoznak
    apiKey = preferences.getString("editTextPsw",
        "gifnta5hc04cur9pqvu4mhg7i7te60nuh42c8n0vz927o7nuaa"); // ezek
                                    // valtoznak
  }

  /**
   * @return
   * @throws ClientProtocolException
   * @throws IOException
   */
  public String httpGet(String method) throws ClientProtocolException,
      IOException {
    DefaultHttpClient httpclient = new DefaultHttpClient();
    HttpGet httpget = new HttpGet(method);

    /* headers */
    httpget.setHeader("Accept", "application/xml");
    httpget.setHeader("Content-Type", "application/xml");

    /* authentication */
    UsernamePasswordCredentials credentials = new UsernamePasswordCredentials(
        username + ":" + apiKey);
    httpclient.getCredentialsProvider().setCredentials(
        new AuthScope(AuthScope.ANY_HOST, AuthScope.ANY_PORT),
        credentials);

    /* execute */
    BasicHttpResponse httpResponse = null;
    httpResponse = (BasicHttpResponse) httpclient.execute(httpget);
    /* return response */
    return TextHelper.GetText(httpResponse);
  }

  /**
   * @param method
   *            - example: "https://api.cashboardapp.com/projects"
   * @param data
   *            - example:
   * @return
   * @throws IOException
   * @throws ClientProtocolException
   */
  public String httpPost(String method, String data)
      throws ClientProtocolException, IOException {
    DefaultHttpClient httpclient = new DefaultHttpClient();
    HttpPost httppost = new HttpPost(method);

    /* headers */
    httppost.setHeader("Accept", "application/xml");
    httppost.setHeader("Content-Type", "application/xml");

    /* authentication */
    UsernamePasswordCredentials credentials = new UsernamePasswordCredentials(
        username + ":" + apiKey);
    httpclient.getCredentialsProvider().setCredentials(
        new AuthScope(AuthScope.ANY_HOST, AuthScope.ANY_PORT),
        credentials);

    StringEntity se = new StringEntity(data, HTTP.UTF_8);
    se.setContentType("text/xml");
    httppost.setEntity(se);

    /* execute */
    BasicHttpResponse httpResponse = null;
    httpResponse = (BasicHttpResponse) httpclient.execute(httppost);
    /* return response */
    return TextHelper.GetText(httpResponse);
  }

}

class TextHelper {
  public static String GetText(InputStream in) {
    String text = "";
    BufferedReader reader = new BufferedReader(new InputStreamReader(in));
    StringBuilder sb = new StringBuilder();
    String line = null;
    try {
      while ((line = reader.readLine()) != null) {
        sb.append(line + "\n");
      }
      text = sb.toString();
    } catch (Exception ex) {

    } finally {
      try {

        in.close();
      } catch (Exception ex) {
      }
    }
    return text;
  }

  public static String GetText(HttpResponse response) {
    String text = "";
    try {
      text = GetText(response.getEntity().getContent());
    } catch (Exception ex) {
    }
    return text;
  }
}

Get Text from HttpResponse

    



//package com.helloandroid.acashboard.utils;

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

import org.apache.http.HttpResponse;

public class TextHelper {
  public static String GetText(InputStream in) {
    String text = "";
    BufferedReader reader = new BufferedReader(new InputStreamReader(in));
    StringBuilder sb = new StringBuilder();
    String line = null;
    try {
      while ((line = reader.readLine()) != null) {
        sb.append(line + "\n");
      }
      text = sb.toString();
    } catch (Exception ex) {

    } finally {
      try {

        in.close();
      } catch (Exception ex) {
      }
    }
    return text;
  }

  public static String GetText(HttpResponse response) {
    String text = "";
    try {
      text = GetText(response.getEntity().getContent());
    } catch (Exception ex) {
    }
    return text;
  }
}

Http Request

    

//package org.acra.util;

import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.InetAddress;
import java.net.InetSocketAddress;
import java.net.Socket;
import java.net.SocketTimeoutException;
import java.net.URL;
import java.net.URLEncoder;
import java.security.GeneralSecurityException;
import java.security.cert.CertificateException;
import java.security.cert.X509Certificate;
import java.util.Map;

import javax.net.ssl.SSLContext;
import javax.net.ssl.SSLSocket;
import javax.net.ssl.TrustManager;
import javax.net.ssl.X509TrustManager;

import org.apache.http.HttpResponse;
import org.apache.http.StatusLine;
import org.apache.http.auth.UsernamePasswordCredentials;
import org.apache.http.client.HttpClient;
import org.apache.http.client.HttpRequestRetryHandler;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.params.ClientPNames;
import org.apache.http.client.params.CookiePolicy;
import org.apache.http.conn.ClientConnectionManager;
import org.apache.http.conn.scheme.LayeredSocketFactory;
import org.apache.http.conn.scheme.PlainSocketFactory;
import org.apache.http.conn.scheme.Scheme;
import org.apache.http.conn.scheme.SchemeRegistry;
import org.apache.http.conn.scheme.SocketFactory;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.auth.BasicScheme;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.impl.conn.tsccm.ThreadSafeClientConnManager;
import org.apache.http.params.BasicHttpParams;
import org.apache.http.params.HttpConnectionParams;
import org.apache.http.params.HttpParams;
import org.apache.http.protocol.BasicHttpContext;
import org.apache.http.protocol.HttpContext;
import org.apache.http.util.EntityUtils;

public final class HttpRequest {

  // private static ACRALog log = new AndroidLogDelegate();

  private static class SocketTimeOutRetryHandler implements
      HttpRequestRetryHandler {

    private final HttpParams httpParams;
    private final int maxNrRetries;

    /**
     * @param httpParams
     *            HttpParams that will be used in the HttpRequest.
     * @param maxNrRetries
     *            Max number of times to retry Request on failure due to
     *            SocketTimeOutException.
     */
    private SocketTimeOutRetryHandler(HttpParams httpParams,
        int maxNrRetries) {
      this.httpParams = httpParams;
      this.maxNrRetries = maxNrRetries;
    }

    @Override
    public boolean retryRequest(IOException exception, int executionCount,
        HttpContext context) {
      if (exception instanceof SocketTimeoutException) {
        if (executionCount <= maxNrRetries) {

          if (httpParams != null) {
            final int newSocketTimeOut = HttpConnectionParams
                .getSoTimeout(httpParams) * 2;
            HttpConnectionParams.setSoTimeout(httpParams,
                newSocketTimeOut);
            // log.d(ACRA.LOG_TAG,
            // "SocketTimeOut - increasing time out to " +
            // newSocketTimeOut + " millis and trying again");
          } else {
            // log.d(ACRA.LOG_TAG,
            // "SocketTimeOut - no HttpParams, cannot increase time out. Trying again with current settings");
          }

          return true;
        }

        // log.d(ACRA.LOG_TAG,
        // "SocketTimeOut but exceeded max number of retries : " +
        // maxNrRetries);
      }

      return false; // To change body of implemented methods use File |
              // Settings | File Templates.
    }
  }

  private String login;
  private String password;
  private int connectionTimeOut = 3000;
  private int socketTimeOut = 3000;
  private int maxNrRetries = 3;

  public void setLogin(String login) {
    this.login = login;
  }

  public void setPassword(String password) {
    this.password = password;
  }

  public void setConnectionTimeOut(int connectionTimeOut) {
    this.connectionTimeOut = connectionTimeOut;
  }

  public void setSocketTimeOut(int socketTimeOut) {
    this.socketTimeOut = socketTimeOut;
  }

  /**
   * The default number of retries is 3.
   * 
   * @param maxNrRetries
   *            Max number of times to retry Request on failure due to
   *            SocketTimeOutException.
   */
  public void setMaxNrRetries(int maxNrRetries) {
    this.maxNrRetries = maxNrRetries;
  }

  /**
   * Posts to a URL.
   * 
   * @param url
   *            URL to which to post.
   * @param parameters
   *            Map of parameters to post to a URL.
   * @throws IOException
   *             if the data cannot be posted.
   */
  public void sendPost(URL url, Map<?, ?> parameters) throws IOException {

    final HttpClient httpClient = getHttpClient();
    final HttpPost httpPost = getHttpPost(url, parameters);

    // log.d(ACRA.LOG_TAG, "Sending request to " + url);

    // TODO Consider using a RequestRetryHandler and if its a
    // SocketTimeoutException to up the SocketTimeout and try again.
    // See
    // http://stackoverflow.com/questions/693997/how-to-set-httpresponse-timeout-for-android-in-java
    // I think SocketTimeOut while waiting for response may be the cause of
    // the multiple crash reports () - I
    final HttpResponse response = httpClient.execute(httpPost,
        new BasicHttpContext());
    if (response != null) {
      final StatusLine statusLine = response.getStatusLine();
      if (statusLine != null) {
        final String statusCode = Integer.toString(response
            .getStatusLine().getStatusCode());
        if (statusCode.startsWith("4") || statusCode.startsWith("5")) {
          throw new IOException("Host returned error code "
              + statusCode);
        }
      }
      final String ret = EntityUtils.toString(response.getEntity());
      // if (ACRA.DEV_LOGGING) log.d(ACRA.LOG_TAG,
      // "HTTP " + (statusLine != null ? statusLine.getStatusCode() :
      // "NoStatusLine#noCode") + " - Returning value:"
      // + ret.substring(0, Math.min(ret.length(), 200)));
    } else {
      // if (ACRA.DEV_LOGGING) log.d(ACRA.LOG_TAG, "HTTP no Response!!");
    }
  }

  /**
   * @return HttpClient to use with this HttpRequest.
   */
  private HttpClient getHttpClient() {
    final HttpParams httpParams = new BasicHttpParams();
    httpParams.setParameter(ClientPNames.COOKIE_POLICY,
        CookiePolicy.RFC_2109);
    HttpConnectionParams
        .setConnectionTimeout(httpParams, connectionTimeOut);
    HttpConnectionParams.setSoTimeout(httpParams, socketTimeOut);
    HttpConnectionParams.setSocketBufferSize(httpParams, 8192);

    final SchemeRegistry registry = new SchemeRegistry();
    registry.register(new Scheme("http", new PlainSocketFactory(), 80));
    registry.register(new Scheme("https", (new FakeSocketFactory()), 443));

    final ClientConnectionManager clientConnectionManager = new ThreadSafeClientConnManager(
        httpParams, registry);
    final DefaultHttpClient httpClient = new DefaultHttpClient(
        clientConnectionManager, httpParams);

    final HttpRequestRetryHandler retryHandler = new SocketTimeOutRetryHandler(
        httpParams, maxNrRetries);
    httpClient.setHttpRequestRetryHandler(retryHandler);

    return httpClient;
  }


  private UsernamePasswordCredentials getCredentials() {
    if (login != null || password != null) {
      return new UsernamePasswordCredentials(login, password);
    }

    return null;
  }

  private HttpPost getHttpPost(URL url, Map<?, ?> parameters)
      throws UnsupportedEncodingException {

    final HttpPost httpPost = new HttpPost(url.toString());

    // log.d(ACRA.LOG_TAG, "Setting httpPost headers");
    final UsernamePasswordCredentials creds = getCredentials();
    if (creds != null) {
      httpPost.addHeader(BasicScheme.authenticate(creds, "UTF-8", false));
    }
    httpPost.setHeader("User-Agent", "Android");
    httpPost.setHeader(
        "Accept",
        "text/html,application/xml,application/xhtml+xml,text/html;q=0.9,text/plain;q=0.8,image/png,*/*;q=0.5");

  private String getParamsAsString(Map<?, ?> parameters)
      throws UnsupportedEncodingException {

    final StringBuilder dataBfr = new StringBuilder();
    for (final Object key : parameters.keySet()) {
      if (dataBfr.length() != 0) {
        dataBfr.append('&');
      }
      final Object preliminaryValue = parameters.get(key);
      final Object value = (preliminaryValue == null) ? ""
          : preliminaryValue;
      dataBfr.append(URLEncoder.encode(key.toString(), "UTF-8"));
      dataBfr.append('=');
      dataBfr.append(URLEncoder.encode(value.toString(), "UTF-8"));
    }

    return dataBfr.toString();
  }
}


class NaiveTrustManager implements X509TrustManager {

  @Override
  public X509Certificate[] getAcceptedIssuers() {
    return new X509Certificate[0];
  }

  @Override
  public void checkClientTrusted(X509Certificate[] x509CertificateArray,
      String string) throws CertificateException {
  }

  @Override
  public void checkServerTrusted(X509Certificate[] x509CertificateArray,
      String string) throws CertificateException {
  }
}

class FakeSocketFactory implements SocketFactory, LayeredSocketFactory {

  private SSLContext sslcontext = null;

  private static SSLContext createEasySSLContext() throws IOException {
    try {
      final SSLContext context = SSLContext.getInstance("TLS");
      context.init(null, new TrustManager[] { new NaiveTrustManager() },
          null);
      return context;
    } catch (GeneralSecurityException e) {
      throw new IOException(e);
    }
  }

  private SSLContext getSSLContext() throws IOException {
    if (this.sslcontext == null) {
      this.sslcontext = createEasySSLContext();
    }
    return this.sslcontext;
  }

  @Override
  public Socket connectSocket(Socket sock, String host, int port,
      InetAddress localAddress, int localPort, HttpParams params)
      throws IOException {
    final int connTimeout = HttpConnectionParams
        .getConnectionTimeout(params);
    final int soTimeout = HttpConnectionParams.getSoTimeout(params);

    final InetSocketAddress remoteAddress = new InetSocketAddress(host,
        port);
    final SSLSocket sslsock = (SSLSocket) ((sock != null) ? sock
        : createSocket());

    if ((localAddress != null) || (localPort > 0)) {
      // we need to bind explicitly
      if (localPort < 0) {
        localPort = 0; // indicates "any"
      }
      final InetSocketAddress isa = new InetSocketAddress(localAddress,
          localPort);
      sslsock.bind(isa);
    }

    sslsock.connect(remoteAddress, connTimeout);
    sslsock.setSoTimeout(soTimeout);

    return sslsock;
  }

  @Override
  public Socket createSocket() throws IOException {
    return getSSLContext().getSocketFactory().createSocket();
  }

  @Override
  public boolean isSecure(Socket arg0) throws IllegalArgumentException {
    return true;
  }

  @Override
  public Socket createSocket(Socket socket, String host, int port,
      boolean autoClose) throws IOException {
    return getSSLContext().getSocketFactory().createSocket(socket, host,
        port, autoClose);
  }

}

Http Downloader

    
//package org.terukusu.android.util;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.UnsupportedEncodingException;
import java.net.SocketTimeoutException;
import java.net.URLDecoder;
import java.net.URLEncoder;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import org.apache.http.Header;
import org.apache.http.NameValuePair;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.methods.HttpUriRequest;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.params.CoreConnectionPNames;

import android.util.Log;

/**
 * Web???????????????????????
 * 
 * @author Teruhiko Kusunoki&lt;<a
 *         href="teru.kusu@gmail.com">teru.kusu@gmail.com</a>&gt;
 * 
 */
public class HttpDownloader {
  /**
   * TAG for {@link android.util.Log}
   */
  private static final String TAG = HttpDownloader.class.getSimpleName();

  public static enum Method {
    POST, GET
  }

  private static final int DEFAULT_BUFFER_SIZE = 4096;
  private static final int DEFAULT_CONNECTION_TIMEOUT = 10000;
  private static final int DEFAULT_SO_TIMEOUT = 10000;

  /** URL?????????????????? */
  private String encoding = StringUtils.getDefaultEncoding();

  private Method method = Method.GET;
  private String url;
  private Map<String, String> queries;
  private Map<String, String> cookies;
  private Map<String, String> headers;
  private int bufferSize = DEFAULT_BUFFER_SIZE;
  private int connectionTimeout = DEFAULT_CONNECTION_TIMEOUT;
  private int soTimeout = DEFAULT_SO_TIMEOUT;

  /** ??????????Content-Length????? */
  private long contentLength;

  /** ??????????????? */
  private long elapsed;

  /** ??????????? */
  private long downloaded;

  /** ??????(bps) */
  private long avarageSpeed;

  /** ??????????????? */
  private boolean isCanceled = false;

  /**
   * ????????????????
   * 
   */
  public HttpDownloader() {
  }

  /**
   * ????????????????
   * 
   * @param url
   *            URL???
   */
  public HttpDownloader(String url) {
    setUrl(url);
  }

  /**
   * ????????????????
   * 
   * @param url
   *            URL
   * @param queries
   *            ???
   */
  public HttpDownloader(String url, Map<String, String> queries) {
    this.url = url;
    this.queries = queries;
  }

  public HttpDownloader(String url, Map<String, String> queries,
      Map<String, String> cookies) {
    this.url = url;
    this.queries = queries;
    this.cookies = cookies;
  }

  /**
   * ????????????
   * 
   * @throws SocketTimeoutException
   *             ????????????????????????
   * @throws ClientProtocolException
   *             ?????????????????
   * @throws IOException
   *             ?????????????
   */
  public HttpResponse execute() throws SocketTimeoutException,
      ClientProtocolException, IOException {
    long start = System.currentTimeMillis();

    HttpUriRequest request = null;

    List<NameValuePair> postParams = new ArrayList<NameValuePair>();

    if (Method.POST == getMethod()) {
      HttpPost post = new HttpPost(getUrl());
      if (getQueries() != null) {
        for (Map.Entry<String, String> entry : getQueries().entrySet()) {
          postParams.add(new BasicNameValuePair(entry.getKey(), entry
              .getValue()));
        }
      }
      post.setEntity(new UrlEncodedFormEntity(postParams, getEncoding()));

      request = post;
    } else {
      StringBuilder sb = new StringBuilder(getUrl());
      if (getQueries() != null) {
        if (sb.indexOf("?") >= 0) {
          sb.append('&');
        } else {
          sb.append('?');
        }
        sb.append(makeQueryString(getQueries()));
      }
      String fullUrl = sb.toString();

      HttpGet get = new HttpGet(fullUrl);

      request = get;
    }

    // ????
    if (getCookies() != null) {
      String cookieStr = makeCookieString(getCookies());
      request.addHeader("Cookie", cookieStr);
    }

    if (getHeaders() != null) {
      for (Map.Entry<String, String> entry : getHeaders().entrySet()) {
        request.addHeader(entry.getKey(),
            URLEncoder.encode(entry.getValue(), getEncoding()));
      }
    }

    HttpClient client = new DefaultHttpClient();
    client.getParams()
        .setIntParameter(CoreConnectionPNames.CONNECTION_TIMEOUT,
            getConnectionTimeout());
    client.getParams().setIntParameter(CoreConnectionPNames.SO_TIMEOUT,
        getSoTimeout());

    org.apache.http.HttpResponse hr = null;
    HttpResponse res = new HttpResponse();

    hr = client.execute(request);

    // ??
    res.setStatusCode(hr.getStatusLine().getStatusCode());

    // header
    for (Header header : hr.getAllHeaders()) {
      res.setHeader(header.getName(), header.getValue());
    }

    // cookie
    for (Header header : hr.getHeaders("Set-Cookie")) {
      String cookieEntry = header.getValue();
      Cookie cookie = Cookie.parseCookie(cookieEntry, null);
      res.setCookie(cookie.getKey(), cookie);
    }

    // body
    if (hr.getEntity() == null) {
      return res;
    }

    // ?????
    Header contentTypeHeader = hr.getEntity().getContentType();
    if (contentTypeHeader != null) {
      String contentType = contentTypeHeader.getValue();
      if (contentType != null) {
        Pattern p = Pattern.compile(
            "text/[^;]+(\\s*;\\s*charset\\s*=\\s*(.+))?",
            Pattern.CASE_INSENSITIVE);
        Matcher m = p.matcher(contentType);
        if (m.find() && !StringUtils.isBlank(m.group(2))) {
          res.setCharacterEncoding(m.group(2));
        }
      }
    }

    setContentLength(hr.getEntity().getContentLength());
    res.setContentLength(hr.getEntity().getContentLength());

    ByteArrayOutputStream baos = null;
    InputStream is = null;
    try {

      baos = new ByteArrayOutputStream();
      is = hr.getEntity().getContent();
      byte[] buff = new byte[getBufferSize()];

      int readSize = 0;
      while (!isCanceled()) {

        if (Thread.interrupted()) {
          // ??????????
          Thread.currentThread().interrupt();
          synchronized (this) {
            isCanceled = true;
          }
          break;
        }

        if ((readSize = is.read(buff)) < 0) {
          // ??????
          break;
        }

        synchronized (this) {
          setDownloaded(getDownloaded() + readSize);
          setElapsed(System.currentTimeMillis() - start);
          long elapsedSec = getElapsed() / 1000;
          if (elapsedSec == 0) {
            setAvarageSpeed(getDownloaded());
          } else {
            setAvarageSpeed(getDownloaded() / elapsedSec);
          }
        }

        baos.write(buff, 0, readSize);
      }
      Log.v(TAG, "downloaded: avarage speed = " + getAvarageSpeed()
          + " bps, downloaded = " + getDownloaded() + " bytes");

      if (isCanceled()) {
        // ?DL??DL???
        request.abort();
      }

    } finally {
      try {
        baos.close();
      } catch (Exception ignore) {
      }
      try {
        is.close();
      } catch (Exception ignore) {
      }
    }

    res.setBody(baos.toByteArray());

    return res;
  }

  /**
   * ?????URL??????????????
   * 
   * @param params
   *            ???
   * @return ??????
   */
  private String makeQueryString(Map<String, String> params) {
    StringBuilder sb = new StringBuilder();
    for (Map.Entry<String, String> entry : params.entrySet()) {
      if (sb.length() > 0) {
        sb.append("&");
      }
      try {
        sb.append(entry.getKey())
            .append("=")
            .append(URLEncoder.encode(entry.getValue(),
                getEncoding()));
      } catch (UnsupportedEncodingException e) {
        throw new RuntimeException(e.getMessage(), e);
      }
    }

    return sb.toString();
  }

  /**
   * Cookie??????????????????????
   * 
   * @param cookies
   *            ???????????????
   * @return Cookie??????????
   */
  private String makeCookieString(Map<String, String> cookies) {
    StringBuilder sb = new StringBuilder();
    for (Map.Entry<String, String> entry : cookies.entrySet()) {
      if (sb.length() > 0) {
        sb.append("; ");
      }
      sb.append(entry.getKey()).append("=").append(entry.getValue());
    }

    return sb.toString();
  }

  /**
   * ????????????
   */
  public synchronized void cancel() {
    isCanceled = true;
  }

  /**
   * ???????(bps)???
   * 
   * @return ???????
   */
  public synchronized long getSpeed() {
    // TODO implement
    return 0;
  }

  /**
   * encoding ???????
   * 
   * @return encoding
   */
  public synchronized String getEncoding() {
    return encoding;
  }

  /**
   * encoding ???????
   * 
   * @param encoding
   *            ????? encoding
   */
  public synchronized void setEncoding(String encoding) {
    this.encoding = encoding;
  }

  /**
   * method ???????
   * 
   * @return method
   */
  public synchronized Method getMethod() {
    return method;
  }

  /**
   * method ???????
   * 
   * @param method
   *            ????? method
   */
  public synchronized void setMethod(Method method) {
    this.method = method;
  }

  /**
   * url ???????
   * 
   * @return url
   */
  public synchronized String getUrl() {
    return url;
  }

  /**
   * url ???????
   * 
   * @param url
   *            ????? url
   */
  public synchronized void setUrl(String url) {
    this.url = url;
  }

  /**
   * queries ???????
   * 
   * @return queries
   */
  public synchronized Map<String, String> getQueries() {
    return queries;
  }

  /**
   * queries ???????
   * 
   * @param queries
   *            ????? queries
   */
  public synchronized void setQueries(Map<String, String> queries) {
    this.queries = queries;
  }

  /**
   * elapsed ???????
   * 
   * @return elapsed
   */
  public synchronized long getElapsed() {
    return elapsed;
  }

  /**
   * elapsed ???????
   * 
   * @param elapsed
   *            ????? elapsed
   */
  public synchronized void setElapsed(long elapsed) {
    this.elapsed = elapsed;
  }

  /**
   * bufferSize ???????
   * 
   * @return bufferSize
   */
  public synchronized int getBufferSize() {
    return bufferSize;
  }

  /**
   * bufferSize ???????
   * 
   * @param bufferSize
   *            ????? bufferSize
   */
  public synchronized void setBufferSize(int bufferSize) {
    this.bufferSize = bufferSize;
  }

  /**
   * cookies ???????
   * 
   * @return cookies
   */
  public synchronized Map<String, String> getCookies() {
    return cookies;
  }

  /**
   * cookies ???????
   * 
   * @param cookies
   *            ????? cookies
   */
  public synchronized void setCookies(Map<String, String> cookies) {
    this.cookies = cookies;
  }

  /**
   * contentLength ???????
   * 
   * @return contentLength
   */
  public synchronized long getContentLength() {
    return contentLength;
  }

  /**
   * contentLength ???????
   * 
   * @param contentLength
   *            ????? contentLength
   */
  protected synchronized void setContentLength(long contentLength) {
    this.contentLength = contentLength;
  }

  /**
   * downloaded ???????
   * 
   * @return downloaded
   */
  public synchronized long getDownloaded() {
    return downloaded;
  }

  /**
   * downloaded ???????
   * 
   * @param downloaded
   *            ????? downloaded
   */
  protected synchronized void setDownloaded(long downloaded) {
    this.downloaded = downloaded;
  }

  /**
   * isCanceled ???????
   * 
   * @return isCanceled
   */
  public synchronized boolean isCanceled() {
    return isCanceled;
  }

  /**
   * isCanceled ???????
   * 
   * @param isCanceled
   *            ????? isCanceled
   */
  protected synchronized void setCanceled(boolean isCanceled) {
    this.isCanceled = isCanceled;
  }

  /**
   * avarageSpeed ???????
   * 
   * @return avarageSpeed
   */
  public synchronized long getAvarageSpeed() {
    return avarageSpeed;
  }

  /**
   * avarageSpeed ???????
   * 
   * @param avarageSpeed
   *            ????? avarageSpeed
   */
  protected synchronized void setAvarageSpeed(long avarageSpeed) {
    this.avarageSpeed = avarageSpeed;
  }

  /**
   * connectionTimeout ???????
   * 
   * @return connectionTimeout
   */
  public synchronized int getConnectionTimeout() {
    return connectionTimeout;
  }

  /**
   * connectionTimeout ???????
   * 
   * @param connectionTimeout
   *            ????? connectionTimeout
   */
  public synchronized void setConnectionTimeout(int connectionTimeout) {
    this.connectionTimeout = connectionTimeout;
  }

  /**
   * soTimeout ???????
   * 
   * @return soTimeout
   */
  public synchronized int getSoTimeout() {
    return soTimeout;
  }

  /**
   * soTimeout ???????
   * 
   * @param soTimeout
   *            ????? soTimeout
   */
  public synchronized void setSoTimeout(int soTimeout) {
    this.soTimeout = soTimeout;
  }

  /**
   * headers ???????
   * 
   * @return headers
   */
  public synchronized Map<String, String> getHeaders() {
    return headers;
  }

  /**
   * headers ???????
   * 
   * @param headers
   *            ????? headers
   */
  public synchronized void setHeaders(Map<String, String> headers) {
    this.headers = headers;
  }
}

/**
 * @author Teruhiko Kusunoki&lt;<a
 *         href="teru.kusu@gmail.com">teru.kusu@gmail.com</a>&gt;
 * 
 */
class HttpResponse {
  private int statusCode;
  private long contentLength;
  private String characterEncoding;
  private final Map<String, String> headers = new HashMap<String, String>();
  private final Map<String, Cookie> cookies = new HashMap<String, Cookie>();
  private byte[] body;

  /**
   *
   */
  public HttpResponse() {
  }

  public void setHeader(String name, String value) {
    this.headers.put(name, value);
  }

  /**
   * header ???????
   * 
   * @return headers
   */
  public String getHeader(String name) {
    return this.headers.get(name);
  }

  /**
   * headers ???????
   * 
   * @return headers
   */
  public Map<String, String> getHeaders() {
    return headers;
  }

  /**
   * ???????????
   * 
   * @param name
   *            ??
   * @return ????
   */
  public Cookie getCookie(String name) {
    return this.cookies.get(name);
  }

  /**
   * ???????????
   * 
   * @param name
   *            ??
   * @param cookie
   *            ????
   */
  public void setCookie(String name, Cookie cookie) {
    this.cookies.put(name, cookie);
  }

  /**
   * cookies ???????
   * 
   * @return cookies
   */
  public Map<String, Cookie> getCookies() {
    return cookies;
  }

  /**
   * body ???????
   * 
   * @return body
   */
  public byte[] getBody() {
    return body;
  }

  /**
   * body ???????
   * 
   * @param body
   *            ????? body
   */
  public void setBody(byte[] body) {
    this.body = body;
  }

  /**
   * statusCode ???????
   * 
   * @return statusCode
   */
  public int getStatusCode() {
    return statusCode;
  }

  /**
   * statusCode ???????
   * 
   * @param statusCode
   *            ????? statusCode
   */
  public void setStatusCode(int statusCode) {
    this.statusCode = statusCode;
  }

  /**
   * contentLength ???????
   * 
   * @return contentLength
   */
  public long getContentLength() {
    return contentLength;
  }

  /**
   * contentLength ???????
   * 
   * @param contentLength
   *            ????? contentLength
   */
  public void setContentLength(long contentLength) {
    this.contentLength = contentLength;
  }

  /**
   * characterEncoding ??????? ????????? text/* ? charset ??????????????????
   * 
   * @return characterEncoding
   */
  public String getCharacterEncoding() {
    return characterEncoding;
  }

  /**
   * characterEncoding ???????
   * 
   * @param characterEncoding
   *            ????? characterEncoding
   */
  public void setCharacterEncoding(String characterEncoding) {
    this.characterEncoding = characterEncoding;
  }
}

/**
 * ?????????????????????????????
 * 
 * @author Teruhiko Kusunoki&lt;<a
 *         href="teru.kusu@gmail.com">teru.kusu@gmail.com</a>&gt;
 * 
 */
class StringUtils {

  /**
   * ??????????????????????????????
   */
  private static final Pattern BLANK_PATTERN = Pattern.compile("^\\s*$");

  /**
   * ????????????????
   * 
   * @param str
   *            ????????
   * @return ?????null???true??????false
   */
  public static boolean isEmpty(String str) {
    return (str == null || str.length() == 0);
  }

  /**
   * null????????????????????????????????????
   * 
   * @param str
   *            ????????
   * @return null???????????????????????????? true??????false?
   */
  public static boolean isBlank(String str) {
    return (str == null || BLANK_PATTERN.matcher(str).matches());
  }

  /**
   * ????????????????????????????????
   * 
   * @return ?????????????????????????
   */
  public static String getDefaultEncoding() {
    return System.getProperty("file.encoding");
  }

  /**
   * Base64??????????????????????????????????? ?: Mzg1OTQyMjczMA== =>
   * 3859422730 => 0xE60A1E0A => 10.30.10.230
   * 
   * @param str
   *            Base64????????????????
   * @return ???????????
   */
  public static String base64toInetAddress(String str) {
    // TODO ??
    throw new UnsupportedOperationException();
    // String numStr = new String(Base64.decode(str, Base64.DEFAULT));
    // int num = Integer.parseInt(numStr);
    //
    // String ipAddr = (num & 0xFF) + "." + (num >> 8 & 0xFF) + "."
    // + (num >> 16 & 0xFF) + "." + (num >> 24 & 0xFF);
    //
    // return ipAddr;
  }
}

/**
 * @author Teruhiko Kusunoki&lt;<a
 *         href="teru.kusu@gmail.com">teru.kusu@gmail.com</a>&gt;
 * 
 */
class Cookie {
  private String key;
  private String value;
  private String path;
  private Date expire;
  private String domain;
  private boolean secure = false;

  /**
   * Set-Cookie ??????????????????????????? ?????????????
   * 
   * @param cookieHeader
   *            Set-Cookie?????
   * @return ??????????
   * @throws ParseException
   *             ?????????
   */
  public static Cookie parseCookie(String cookieHeader) {
    return parseCookie(cookieHeader, null);
  }

  /**
   * Set-Cookie ???????????????????????????
   * 
   * @param cookieHeader
   *            Set-Cookie?????
   * @param encode
   *            cookie???????. null?????????????????
   * @return ??????????
   * @throws ParseException
   *             ?????????
   */
  public static Cookie parseCookie(String cookieHeader, String encode) {

    Cookie c = new Cookie();
    for (String str : cookieHeader.split("\\s*;\\s*")) {
      int index = str.indexOf('=');
      if (index < 0) {
        if ("secure".equals(str.toLowerCase())) {
          c.setSecure(true);
        }
        continue;
      }

      String key = str.substring(0, index).toLowerCase();
      String value = str.substring(index + 1);

      if ("expires".equals(key.toLowerCase())) {
        SimpleDateFormat sdf = new SimpleDateFormat(
            "EEE, d-MMM-yyyy HH:mm:ss ZZZ", Locale.US);
        Date date = null;
        try {
          date = sdf.parse(value);
        } catch (ParseException e) {
          throw new RuntimeException(e.getMessage(), e);
        }
        c.setExpire(date);
      } else if ("domain".equals(key.toLowerCase())) {
        c.setDomain(value);
      } else if ("path".equals(key.toLowerCase())) {
        c.setPath(value);
      } else {
        c.setKey(key);
        if (StringUtils.isBlank(encode)) {
          c.setValue(value);
        } else {
          try {
            c.setValue(URLDecoder.decode(value, encode));
          } catch (UnsupportedEncodingException e) {
            throw new RuntimeException(e.getMessage(), e);
          }
        }
      }
    }

    return c;
  }

  /**
   * key ???????
   * 
   * @return key
   */
  public String getKey() {
    return key;
  }

  /**
   * key ???????
   * 
   * @param key
   *            ????? key
   */
  public void setKey(String key) {
    this.key = key;
  }

  /**
   * value ???????
   * 
   * @return value
   */
  public String getValue() {
    return value;
  }

  /**
   * value ???????
   * 
   * @param value
   *            ????? value
   */
  public void setValue(String value) {
    this.value = value;
  }

  /**
   * path ???????
   * 
   * @return path
   */
  public String getPath() {
    return path;
  }

  /**
   * path ???????
   * 
   * @param path
   *            ????? path
   */
  public void setPath(String path) {
    this.path = path;
  }

  /**
   * expire ???????
   * 
   * @return expire
   */
  public Date getExpire() {
    return expire;
  }

  /**
   * expire ???????
   * 
   * @param expire
   *            ????? expire
   */
  public void setExpire(Date expire) {
    this.expire = expire;
  }

  /**
   * domain ???????
   * 
   * @return domain
   */
  public String getDomain() {
    return domain;
  }

  /**
   * domain ???????
   * 
   * @param domain
   *            ????? domain
   */
  public void setDomain(String domain) {
    this.domain = domain;
  }

  /**
   * secure ???????
   * 
   * @return secure
   */
  public boolean isSecure() {
    return secure;
  }

  /**
   * secure ???????
   * 
   * @param secure
   *            ????? secure
   */
  public void setSecure(boolean secure) {
    this.secure = secure;
  }
}

Is Http Url Available

    
//package net.bible.service.common;

import java.io.IOException;
import java.net.HttpURLConnection;
import java.net.URL;
//
class CommonUtils {
  public static boolean isHttpUrlAvailable(String urlString) {
    HttpURLConnection connection = null;
    try {
      // might as well test for the url we need to access
      URL url = new URL(urlString);

      connection = (HttpURLConnection) url.openConnection();
      connection.setConnectTimeout(3000);
  
      connection.connect();
      boolean success = (connection.getResponseCode() == HttpURLConnection.HTTP_OK);
  
      return success;
    } catch (IOException e) {
  
      return false;
    } finally {
      if (connection != null) {
        connection.disconnect();
      }
    }
  }

Http Retriever

    
//package com.si.anddos.search;

import java.io.IOException;
import java.io.InputStream;
import java.net.URI;
import java.net.URLEncoder;

import org.apache.http.HttpEntity;
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.util.EntityUtils;


import android.net.Uri;
import android.util.Log;

public class HttpRetriever {
  
  private DefaultHttpClient client = new DefaultHttpClient();  
  
  public String retrieve(String uri) {
    
    HttpGet getRequest = new HttpGet(uri);
    
        
    try {
      
      
      HttpResponse getResponse = client.execute(getRequest);
      final int statusCode = getResponse.getStatusLine().getStatusCode();
      
      if (statusCode != HttpStatus.SC_OK) { 
              Log.w(getClass().getSimpleName(), "Error " + statusCode + " for URL " + uri.toString()); 
              return null;
          }
      
      HttpEntity getResponseEntity = getResponse.getEntity();
      
      if (getResponseEntity != null) {
        return EntityUtils.toString(getResponseEntity);
      }
      
    } 
    catch (IOException e) {
      getRequest.abort();
          Log.w(getClass().getSimpleName(), "Error for URL " + uri.toString(), e);
    }
    
    return null;
    
  }
  
  public InputStream retrieveStream(String url) {
    
    HttpGet getRequest = new HttpGet(url);
        
    try {
      
      HttpResponse getResponse = client.execute(getRequest);
      final int statusCode = getResponse.getStatusLine().getStatusCode();
      
      if (statusCode != HttpStatus.SC_OK) { 
              Log.w(getClass().getSimpleName(), "Error " + statusCode + " for URL " + url); 
              return null;
          }

      HttpEntity getResponseEntity = getResponse.getEntity();
      return getResponseEntity.getContent();
      
    } 
    catch (IOException e) {
      getRequest.abort();
          Log.w(getClass().getSimpleName(), "Error for URL " + url, e);
    }
    
    return null;
    
  }
  

}

Receive Response from HttpURLConnection

    
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;

 class ConnectionUtils {

  public static String receiveResponse(HttpURLConnection conn)
      throws IOException {
    conn.setConnectTimeout(10000);
    conn.setReadTimeout(10000);
    // retrieve the response from server
    InputStream is = null;
    try {
      is = conn.getInputStream();
      int ch;
      StringBuffer sb = new StringBuffer();
      while ((ch = is.read()) != -1) {
        sb.append((char) ch);
      }
      return sb.toString();
    } catch (IOException e) {
      throw e;
    } finally {
      if (is != null) {
        is.close();
      }
    }
  }

}

Print http headers. Useful for debugging.

    
import java.net.MalformedURLException;
import java.net.URL;

import org.apache.http.Header;

class Utilities {
  /**
   * Print http headers. Useful for debugging.
   * 
   * @param headers
   */
  public static String getHeadersAsString(Header[] headers) {

    StringBuffer s = new StringBuffer("Headers:");
    s.append("------------");
    for (Header h : headers)
      s.append(h.toString());
    s.append("------------");
    return s.toString();
  }

}

Return the base URL from the given URL. Example: http://foo.org/abc.html -> http://foo.org/

    
import java.net.MalformedURLException;
import java.net.URL;

import org.apache.http.Header;

class Utilities {
  /**
   * Return the base URL from the given URL. Example: http://foo.org/abc.html -> http://foo.org/
   * 
   * @param surl
   * @return The base URL.
   */
  public static String getBaseUrl(String surl) {
    URL url;
    try {
      url = new URL(surl);
      System.out.println("getHost: " + url.getHost());
      return "http://" + url.getHost() + "/";
    } catch (MalformedURLException e) {
      e.printStackTrace();
    }
    return null;
  }

}

Send message with HttpPost

    
//package com.javaseed;

import java.io.IOException;
import java.util.List;

import org.apache.http.NameValuePair;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.ResponseHandler;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.BasicResponseHandler;
import org.apache.http.impl.client.DefaultHttpClient;

public class HttpClientUtil {

  protected String sendMsg(String url) throws ClientProtocolException,
      IOException {
    return sendMsg(url, null);
  }

  protected String sendMsg(String url, List<NameValuePair> params)
      throws ClientProtocolException, IOException {
    HttpClient httpclient = new DefaultHttpClient();

    HttpPost httppost = new HttpPost(url);

    System.out.println("executing request " + httppost.getURI());

    if (params != null) {
      UrlEncodedFormEntity entity = new UrlEncodedFormEntity(params,
          "UTF-8");

      httppost.setEntity(entity);

    }

    ResponseHandler<String> responseHandler = new BasicResponseHandler();

    String responseBody = httpclient.execute(httppost, responseHandler);

    httpclient.getConnectionManager().shutdown();

    return responseBody;

  }

}

Get Http Stream

    
//package com.dedrake.kswine;

import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLConnection;

import android.graphics.Bitmap;
import android.graphics.BitmapFactory;

class Utilities {

  public static InputStream getHttpStream(String urlString) throws IOException {
    InputStream in = null;
    int response = -1;
               
    URL url = new URL(urlString); 
    URLConnection conn = url.openConnection();
                 
    if (!(conn instanceof HttpURLConnection)) { throw new IOException("Not an HTTP connection"); }
        
  try {
    HttpURLConnection hcn = (HttpURLConnection) conn;
    hcn.setAllowUserInteraction(false);
    hcn.setInstanceFollowRedirects(true);
    hcn.setRequestMethod("GET");
    hcn.connect();

    response = hcn.getResponseCode();
    if (response == HttpURLConnection.HTTP_OK) { in = hcn.getInputStream(); }
  }
    catch (Exception ex) {
      throw new IOException("Error connecting");            
    }
    
    return in;     
  }
  
  public static Bitmap getUrlImage(String urlString) {        
    Bitmap bmp = null;
    InputStream in = null;
    
    try {
      in = getHttpStream(urlString);
      bmp = BitmapFactory.decodeStream(in);
      in.close();
    } 
    catch (IOException e) {

    }
    
    return bmp;                
  }
  
  public static String getUrlText(String urlString) {
    InputStream in = null;
      
    try {
      in = getHttpStream(urlString);
    } 
    catch (IOException e) {
      return "";
    }
      
    InputStreamReader isr = new InputStreamReader(in);
    int charRead;
    StringBuilder sb = new StringBuilder();
    char[] ib = new char[2000];          
    
    try {
      while ((charRead = isr.read(ib)) > 0) {                    
        String readString = String.copyValueOf(ib, 0, charRead);                    
        sb.append(readString);
        ib = new char[2000];
      }
      in.close();
    } 
    catch (IOException e) {
      return "";
    }    
    return sb.toString();        
  }
}

Generic Object Http Loader

    


import java.io.IOException;
import java.io.InputStream;
import java.net.URI;
import java.net.URISyntaxException;

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

public abstract class HttpClient<T>
{    
  /**
   * Effectue une requ?te HTTP GET et r?cup?re un <code>T</code> en retour
   * @param url L'url concern?e
   * @return Un <code>T</code> contenant la r?ponse
   * @throws IOException Si un probl?me intervient durant la requ?te
   * @throws URISyntaxException Si l'url est foireuse
   */
  public T getResponse(String url) throws IOException, URISyntaxException
  {
    DefaultHttpClient client = new DefaultHttpClient();
    InputStream data = null;
    URI uri = new URI(url);
    HttpGet method = new HttpGet(uri);
    method.setHeader("User-Agent", "Mozilla /4.0 (compatible; MSIE 6.0; Windows CE; IEMobile 7.6) Vodafone/1.0/SFR_v1615/1.56.163.8.39");

    HttpResponse response = client.execute(method);
    HttpEntity entity = response.getEntity();
    T result = null;
    if (entity != null)
    {
      try
      {
        data = entity.getContent();
        result = transformStream(data);
      }
      catch (IOException e)
      {
        throw e;
      }
      catch (RuntimeException e)
      {
        method.abort();
        throw e;
      }
      finally
      {
        if (entity != null) entity.consumeContent();
        client.getConnectionManager().shutdown();  
      }
    }
    return result;
  }
  
  protected abstract T transformStream(InputStream is) throws IOException;    
}

Http Get and DefaultHttpClient

    

//package com.joke.praser;

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

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

public class HttpUtils {

  private static final String tag = "HttpUtils";

  private static final int DEFAULT_BUFFER_SIZE = 8192;

  /**
   * ????
   * 
   * @param url
   * @return
   */
  public static String httpGet(String url) {

    DefaultHttpClient httpclient = new DefaultHttpClient();
    try {
      HttpGet httpget = new HttpGet(url);
      httpget.addHeader("User-Agent", "ie 6");
      HttpResponse response = httpclient.execute(httpget);
      HttpEntity entity = response.getEntity();
      return generateString(entity.getContent());
    } catch (IOException e) {
      e.printStackTrace();
      return null;
    }

  }
  
  /**
   * ????
   * 
   * @param url
   * @return
   */
  public static InputStream httpGetIS(String url) {

    DefaultHttpClient httpclient = new DefaultHttpClient();
    try {
      HttpGet httpget = new HttpGet(url);
      httpget.addHeader("User-Agent", "ie 6");
      HttpResponse response = httpclient.execute(httpget);
      HttpEntity entity = response.getEntity();
      return entity.getContent();
    } catch (IOException e) {
      e.printStackTrace();
      return null;
    }

  }

  private static String generateString(InputStream stream) {
    StringBuilder sb = new StringBuilder();
    InputStreamReader reader = null;
    try {
      reader = new InputStreamReader(stream, "utf-8");
      BufferedReader buffer = new BufferedReader(reader);
      String cur;
      while ((cur = buffer.readLine()) != null) {
        sb.append(cur + "\n");
      }

    } catch (UnsupportedEncodingException e1) {
      e1.printStackTrace();
      return null;
    } catch (IOException e) {
      e.printStackTrace();
      return null;
    } finally {
      if (reader != null) {
        try {
          reader.close();
          reader = null;
        } catch (IOException e) {
          e.printStackTrace();
        }
      }
      if (stream != null) {
        try {
          stream.close();
          stream = null;
        } catch (IOException e) {
          e.printStackTrace();
        }
      }
    }

    return sb.toString();
  }

}

Gets http output from URL

//package net.mandaria.radioreddit.utils;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.List;

import org.apache.http.NameValuePair;
import org.apache.http.client.ClientProtocolException;

import android.content.Context;
import android.net.Uri;

public class HTTPUtil
{

  public static String slurp(InputStream in) throws IOException
  {
    StringBuffer out = new StringBuffer();
    byte[] b = new byte[4096];
    for(int n; (n = in.read(b)) != -1;)
    {
      out.append(new String(b, 0, n));
    }
    return out.toString();
  }

  // gets http output from URL
  public static String get(Context c, String url) throws ClientProtocolException, IOException
  {
    HttpURLConnection conn = (HttpURLConnection) new URL(url).openConnection();
    // conn.setRequestProperty("User-Agent", Utils.USER_AGENT);

    // Account a = Account.getActiveAccount(c); // Account is just a class to hold the reddit login cookie
    // if(a != null)
    // {
    // conn.setRequestProperty("Cookie", "reddit_session=" + a.redditSession); // I tried sending cookies in other ways but none worked on Android 2.1 or 2.2 except this
    // }

    String output = HTTPUtil.slurp(conn.getInputStream());
    conn.getInputStream().close();

    return output;
  }

  // posts data to http, gets output from URL
  public static String post(Context c, String url, List<NameValuePair> params) throws ClientProtocolException, IOException
  {
    StringBuilder post = new StringBuilder(); // Using the built in method to post a List<NameValuePair> fails on Android 2.1 / 2.2.... manually post the data
    for(NameValuePair p : params)
    {
      post.append(Uri.encode(p.getName()) + "=" + Uri.encode(p.getValue()) + "&");
    }
    post.deleteCharAt(post.length() - 1); // Remove trailing &

    HttpURLConnection conn = (HttpURLConnection) new URL(url).openConnection();
    conn.setDoOutput(true);
    // conn.setRequestProperty("User-Agent", Utils.USER_AGENT);
    conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
    conn.setRequestProperty("Content-Length", Integer.toString(post.length()));

    // Account a = Account.getActiveAccount(c);
    // if(a != null)
    // {
    // conn.setRequestProperty("Cookie", "reddit_session=" + a.redditSession);
    // }

    OutputStream os = conn.getOutputStream();
    os.write(post.toString().getBytes());

    String output = HTTPUtil.slurp(conn.getInputStream());
    conn.getInputStream().close();

    return output;
  }
}

Util for Http Get

    

//package name.nanek.vidaccessor.android;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.List;
import java.util.zip.GZIPInputStream;

import org.apache.http.Header;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.methods.HttpRequestBase;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.protocol.HTTP;
import org.json.JSONObject;

import android.util.Log;

class HttpUtil {
  /**
   * This is the developer key for accessing the YouTube data API. 
   * See details here to get one: 
   * http://code.google.com/apis/youtube/2.0/developers_guide_protocol.html#Developer_Key 
   * Then paste it in as the value of this String constant.
   */
  public static final String YOUTUBE_API_DEVELOPER_KEY = "INSERT_YOUR_DEV_KEY_HERE";
  
  private static final String LOG = HttpUtil.class.getSimpleName();

    public static String getStringResult(String url, List<NameValuePair> postData) {
      
      Log.e(LOG, "Contacting URL: " + url);
      
    try {
      DefaultHttpClient client = new DefaultHttpClient();
      HttpRequestBase request;
      if ( null == postData ) {
        request = new HttpGet(url);
      } else {
        HttpPost postRequest = new HttpPost(url);
        //StringEntity se = new StringEntity(postData);
        UrlEncodedFormEntity se = new UrlEncodedFormEntity(postData, HTTP.UTF_8);
        postRequest.setEntity(se);
        request = postRequest;
      }
      request.setHeader("Accept", "application/json");
      request.setHeader("Content-type", "application/json");
      request.setHeader("Accept-Encoding", "gzip");

      HttpResponse response = (HttpResponse) client.execute(request);

      HttpEntity entity = response.getEntity();
      if (entity != null) {
        InputStream instream = entity.getContent();
        Header contentEncoding = response.getFirstHeader("Content-Encoding");
        if (contentEncoding != null && contentEncoding.getValue().equalsIgnoreCase("gzip")) {
          instream = new GZIPInputStream(instream);
        }
        String resultString = convertStreamToString(instream);
        instream.close();
        return resultString;
      }

    } catch (Exception e) {
      Log.e(LOG, "Error getting results.", e);
    }
    return null;
      
      
    }
    
    public static JSONObject getJSONResults(String url) {
      
    try {
        String resultString = getStringResult(url, null);  
      
        Log.i(LOG, "results = " + resultString);
        //Remove wrapping []
        //resultString = resultString.substring(1, resultString.length() - 1);

        JSONObject jsonObjRecv = new JSONObject(resultString);

        return jsonObjRecv;

    } catch (Exception e) {
      Log.e(LOG, "Error getting results.", e);
    }
    return null;
      
      
    }

  private static String convertStreamToString(InputStream is) {
    BufferedReader reader = new BufferedReader(new InputStreamReader(is));
    StringBuilder sb = new StringBuilder();
    String line = null;
    try {
      while ((line = reader.readLine()) != null) {
        sb.append(line + "\n");
      }
    } catch (IOException e) {
      e.printStackTrace();
    } finally {
      try {
        is.close();
      } catch (IOException e) {
        e.printStackTrace();
      }
    }
    return sb.toString();
  }
}

do Http Get Request and return the status code

    
import java.net.HttpURLConnection;
import java.net.URL;

import android.util.Log;

class Main {
  public static int doHttpGetRequest(String url) {
    try {
      HttpURLConnection conn = (HttpURLConnection) (new URL(url))
          .openConnection();
      conn.setUseCaches(false);
      conn.connect();
      int status = conn.getResponseCode();
      conn.disconnect();
      return status;
    } catch (Exception e) {
      Log.e("doHttpGetRequest", e.toString());
    }
    return 0;
  }

}
Http Get
//package net.sarangnamu.android;


import java.io.BufferedOutputStream;
import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLDecoder;
import java.net.URLEncoder;

import android.content.Context;
import android.os.Bundle;
import android.webkit.CookieManager;
import android.webkit.CookieSyncManager;

final class Util {


  public static String openURL(String url, String method, Bundle params)
    throws MalformedURLException, IOException {

    final String boundary = "sarangnamu.net_boundry-------------------";
    final String endLine = "\r\n";

    OutputStream os;

    if (method.equals("GET")) {
      url = url + "?" + percentEncode(params);
    }

    HttpURLConnection conn = (HttpURLConnection) new URL(url).openConnection();
    conn.setRequestProperty("User-Agent",
                System.getProperties().getProperty("http.agent") + " sarangnamu.net");

    if (!method.equals("GET")) {
      Bundle dataParams = new Bundle();

      for (String key : params.keySet()) {
        if (params.getByteArray(key) != null) {
          dataParams.putByteArray(key, params.getByteArray(key));
        }
      }

      if (!params.containsKey("method")) {
        params.putString("method", method);
      }

      conn.setRequestMethod("POST");
      conn.setRequestProperty("Content-Type", "multipart/form-data;boundary=" + boundary);
      conn.setDoOutput(true);
      conn.setDoInput(true);
      conn.setRequestProperty("Connection", "Keep-Alive");
      conn.connect();

      os = new BufferedOutputStream(conn.getOutputStream());
      os.write(("---" + boundary + endLine).getBytes());
      os.write(percentEncodeBody(params, boundary).getBytes());
      os.write((endLine + "---" + boundary + endLine).getBytes());

      if (!dataParams.isEmpty()) {
        for (String key : dataParams.keySet()) {
          os.write(("Content-Disposition: form-data; filename=\"" + key + "\"" + endLine).getBytes());
                    os.write(("Content-Type: content/unknown" + endLine + endLine).getBytes());
                    os.write(dataParams.getByteArray(key));
                    os.write((endLine + "--" + boundary + endLine).getBytes());
        }
      }

      os.flush();
    }

    String response = "";
        try {
            response = read(conn.getInputStream());
        } catch (FileNotFoundException e) {
            // Error Stream contains JSON that we can parse to a FB error
            response = read(conn.getErrorStream());
        }
        return response;
  }

  private static String read(InputStream in) throws IOException {
        StringBuilder sb = new StringBuilder();
        BufferedReader r = new BufferedReader(new InputStreamReader(in), 1000);
        for (String line = r.readLine(); line != null; line = r.readLine()) {
            sb.append(line);
        }
        in.close();
        return sb.toString();
    }

  /*
   * percent encode
   */

  public static String percentEncodeBody(Bundle parameters, String boundary) {
    if (parameters == null)
      return "";

      StringBuilder sb = new StringBuilder();

          for (String key : parameters.keySet()) {
              if (parameters.getByteArray(key) != null) {
                  continue;
              }

              sb.append("Content-Disposition: form-data; name=\"" + key +
                    "\"\r\n\r\n" + parameters.getString(key));
              sb.append("\r\n" + "--" + boundary + "\r\n");
          }

          return sb.toString();
  }

  public static String percentEncode(Bundle parameters) {
    if (parameters == null) {
        return "";
    }

      StringBuilder sb = new StringBuilder();
      boolean first = true;
      for (String key : parameters.keySet()) {
        if (first) first = false; else sb.append("&");
            sb.append(URLEncoder.encode(key) + "=" +
                        URLEncoder.encode(parameters.getString(key)));
          }
          return sb.toString();
  }

  public static Bundle percentDecode(String s) {
    Bundle params = new Bundle();
    if (s != null) {
        String array[] = s.split("&");
        for (String parameter : array) {
          String v[] = parameter.split("=");
              params.putString(URLDecoder.decode(v[0]),
                      URLDecoder.decode(v[1]));
        }
      }
    return params;
  }



    public static void clearCookies(Context context) {
     
        @SuppressWarnings("unused")
        CookieSyncManager cookieSyncMngr =
            CookieSyncManager.createInstance(context);
        CookieManager cookieManager = CookieManager.getInstance();
        cookieManager.removeAllCookie();
    }

}
implements HttpClient

import java.io.IOException;

import org.apache.http.HttpHost;
import org.apache.http.HttpRequest;
import org.apache.http.HttpRequestInterceptor;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.ResponseHandler;
import org.apache.http.client.methods.HttpUriRequest;
import org.apache.http.client.params.HttpClientParams;
import org.apache.http.client.protocol.ClientContext;
import org.apache.http.conn.ClientConnectionManager;
import org.apache.http.conn.scheme.PlainSocketFactory;
import org.apache.http.conn.scheme.Scheme;
import org.apache.http.conn.scheme.SchemeRegistry;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.impl.conn.tsccm.ThreadSafeClientConnManager;
import org.apache.http.params.BasicHttpParams;
import org.apache.http.params.HttpConnectionParams;
import org.apache.http.params.HttpParams;
import org.apache.http.params.HttpProtocolParams;
import org.apache.http.protocol.BasicHttpContext;
import org.apache.http.protocol.BasicHttpProcessor;
import org.apache.http.protocol.HttpContext;


public final class AndroidHttpClient implements HttpClient {
  public static final AndroidHttpClient client = AndroidHttpClient.newInstance("wordsearch");


  private static final ThreadLocal<Boolean> sThreadBlocked =
      new ThreadLocal<Boolean>();


  private static final HttpRequestInterceptor sThreadCheckInterceptor =
      new HttpRequestInterceptor() {
        public void process(HttpRequest request, HttpContext context) {
          if (Boolean.TRUE.equals(sThreadBlocked.get())) {
            throw new RuntimeException("This thread forbids HTTP requests");
          }
        }
      };


  public static AndroidHttpClient newInstance(String userAgent) {
    HttpParams params = new BasicHttpParams();

    // Turn off stale checking.  Our connections break all the time anyway,
    // and it's not worth it to pay the penalty of checking every time.
    HttpConnectionParams.setStaleCheckingEnabled(params, false);

    // Default connection and socket timeout of 20 seconds.  Tweak to taste.
    HttpConnectionParams.setConnectionTimeout(params, 20 * 1000);
    HttpConnectionParams.setSoTimeout(params, 20 * 1000);
    HttpConnectionParams.setSocketBufferSize(params, 8192);

    // Don't handle redirects -- return them to the caller.  Our code
    // often wants to re-POST after a redirect, which we must do ourselves.
    HttpClientParams.setRedirecting(params, false);
    HttpClientParams.setAuthenticating(params, false);

    // Set the specified user agent and register standard protocols.
    HttpProtocolParams.setUserAgent(params, userAgent);
    SchemeRegistry schemeRegistry = new SchemeRegistry();
    schemeRegistry.register(new Scheme("http", PlainSocketFactory.getSocketFactory(), 80));
//    schemeRegistry.register(new Scheme("https", SSLSocketFactory.getSocketFactory(), 443));
    ClientConnectionManager manager = new ThreadSafeClientConnManager(params, schemeRegistry);

    // We use a factory method to modify superclass initialization
    // parameters without the funny call-a-static-method dance.
    return new AndroidHttpClient(manager, params);
  }

  private final HttpClient delegate;


  private AndroidHttpClient(ClientConnectionManager ccm, HttpParams params) {
    this.delegate = new DefaultHttpClient(ccm, params) {
      @Override
      protected BasicHttpProcessor createHttpProcessor() {
        // Add interceptor to prevent making requests from main thread.
        BasicHttpProcessor processor = super.createHttpProcessor();
        processor.addRequestInterceptor(sThreadCheckInterceptor);
        return processor;
      }

      @Override
      protected HttpContext createHttpContext() {
        // Same as DefaultHttpClient.createHttpContext() minus the
        // cookie store.
        HttpContext context = new BasicHttpContext();
        context.setAttribute(ClientContext.AUTHSCHEME_REGISTRY, getAuthSchemes());
        context.setAttribute(ClientContext.COOKIESPEC_REGISTRY, getCookieSpecs());
        context.setAttribute(ClientContext.CREDS_PROVIDER, getCredentialsProvider());
        return context;
      }
    };
  }

  /**
   * Release resources associated with this client.  You must call this,
   * or significant resources (sockets and memory) may be leaked.
   */
  public void close() {
    getConnectionManager().shutdown();
  }

  public HttpParams getParams() {
    return delegate.getParams();
  }

  public ClientConnectionManager getConnectionManager() {
    return delegate.getConnectionManager();
  }

  public HttpResponse execute(HttpUriRequest request) throws IOException {
    return delegate.execute(request);
  }

  public HttpResponse execute(HttpUriRequest request, HttpContext context) throws IOException {
    return delegate.execute(request, context);
  }

  public HttpResponse execute(HttpHost target, HttpRequest request) throws IOException {
    return delegate.execute(target, request);
  }

  public HttpResponse execute(HttpHost target, HttpRequest request,
                              HttpContext context) throws IOException {
    return delegate.execute(target, request, context);
  }

  public <T> T execute(HttpUriRequest request, ResponseHandler<? extends T> responseHandler) throws IOException {
    return delegate.execute(request, responseHandler);
  }

  public <T> T execute(HttpUriRequest request, ResponseHandler<? extends T> responseHandler, HttpContext context)
      throws IOException {
    return delegate.execute(request, responseHandler, context);
  }

  public <T> T execute(HttpHost target, HttpRequest request, ResponseHandler<? extends T> responseHandler)
      throws IOException {
    return delegate.execute(target, request, responseHandler);
  }

  public <T> T execute(HttpHost target, HttpRequest request,
                       ResponseHandler<? extends T> responseHandler,
                       HttpContext context)
      throws IOException {
    return delegate.execute(target, request, responseHandler, context);
  }

}

Get File From HTTP

    
import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.net.URL;
import java.net.URLConnection;

import android.util.Log;

class Main {
  public static File GetFileFromHTTP(String URL, String TempFilePrefix,
      String TempFileSuffix) {
    try {
      URL url = new URL(URL);
      URLConnection conn = url.openConnection();
      conn.setConnectTimeout(10000);
      conn.connect();

      InputStream is = conn.getInputStream();
      if (is != null) {
        File f = File.createTempFile(TempFilePrefix, TempFileSuffix);
        FileOutputStream fos = new FileOutputStream(f);
        byte buff[] = new byte[128];

        while (true) {
          int readbyte = is.read(buff);

          if (readbyte <= 0)
            break;

          fos.write(buff, 0, readbyte);
        }

        is.close();
        return f;
      } else
        return null;
    } catch (Exception e) {
      if (e.getMessage() != null)
        //Log.w(Common.LOGCAT_TAG, e.getMessage());
        ;
      else
        e.printStackTrace();

      return null;
    }
  }
}

Make all redirects to go to http in stead of https

    

//package com.sputnik.wispr.util;

import java.net.URI;
import java.net.URISyntaxException;

import org.apache.http.HttpResponse;
import org.apache.http.ProtocolException;
import org.apache.http.impl.client.DefaultRedirectHandler;
import org.apache.http.protocol.HttpContext;

import android.util.Log;

/**
 * Make all redirects to go to http in stead of http<b>s</b><br/>
 * Only used for testing purposes
 */
public class RemoveHttpsRedirectHandler extends DefaultRedirectHandler {
  private static String TAG = RemoveHttpsRedirectHandler.class.getName();

  @Override
  public URI getLocationURI(HttpResponse response, HttpContext context) throws ProtocolException {
    String uri = super.getLocationURI(response, context).toString();
    if (uri.startsWith("https")) {
      uri = uri.replaceFirst("https", "http");
      Log.d(TAG, "Removing https from redirect:" + uri);
    }
    URI notSafeUri = null;
    try {
      notSafeUri = new URI(uri);
    } catch (URISyntaxException e) {
      Log.e(TAG, "error change URI", e);
    }
    return notSafeUri;
  }
}

New Http Client Manager

    

//package com.filmatchs.utils;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.List;

import org.apache.http.Header;
import org.apache.http.HttpEntity;
import org.apache.http.HttpEntityEnclosingRequest;
import org.apache.http.HttpHost;
import org.apache.http.HttpResponse;
import org.apache.http.auth.AuthScope;
import org.apache.http.auth.UsernamePasswordCredentials;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.methods.HttpDelete;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.methods.HttpPut;
import org.apache.http.conn.scheme.PlainSocketFactory;
import org.apache.http.conn.scheme.Scheme;
import org.apache.http.conn.ssl.SSLSocketFactory;
import org.apache.http.impl.client.DefaultHttpClient;

import android.util.Log;

public class NewHttpClientManager {

  public static String LOG_TAG = "NewHttpClientManager";

  public static int METHOD_GET = 1;
  public static int METHOD_POST = 2;
  public static int METHOD_PUT = 3;
  public static int METHOD_DELETE = 4;

  private String result = "";

  public NewHttpClientManager(String url, int method,
      ArrayList<Header> headers, HttpEntity entity,
      UsernamePasswordCredentials credential)
      throws ClientProtocolException, IOException {
    try {
      result = connectResponse(url, method, headers, entity, credential, null);
    } catch (ClientProtocolException ex) {
      Log.e(LOG_TAG, "ClientProtocol Exception");
      ex.printStackTrace();
    } catch (IOException ex) {
      Log.e(LOG_TAG, "IO Exception");
      ex.printStackTrace();
    }
  }
  
  public NewHttpClientManager(String url, int method,
      ArrayList<Header> headers, HttpEntity entity,
      UsernamePasswordCredentials credential, HttpHost host)
      throws ClientProtocolException, IOException {
    try {
      result = connectResponse(url, method, headers, entity, credential, host);
    } catch (ClientProtocolException ex) {
      Log.e(LOG_TAG, "ClientProtocol Exception");
      ex.printStackTrace();
    } catch (IOException ex) {
      Log.e(LOG_TAG, "IO Exception");
      ex.printStackTrace();
    }
  }


  public static String connectResponse(String url, int method,
      List<Header> headers, HttpEntity entity,
      UsernamePasswordCredentials credential, HttpHost host)
      throws ClientProtocolException, IOException {
    DefaultHttpClient httpClient = new DefaultHttpClient();
    HttpResponse response;

    String retval = null;

    HttpEntityEnclosingRequest heer = null;

    // setting scheme for http/https
    final SSLSocketFactory sslSocketFactory = SSLSocketFactory
        .getSocketFactory();
    sslSocketFactory
        .setHostnameVerifier(SSLSocketFactory.BROWSER_COMPATIBLE_HOSTNAME_VERIFIER);
    httpClient.getConnectionManager().getSchemeRegistry().register(
        new Scheme("http", PlainSocketFactory.getSocketFactory(), 80));
    httpClient.getConnectionManager().getSchemeRegistry().register(
        new Scheme("https", sslSocketFactory, 443));

    if (method == METHOD_POST) {
      // ------------------ POST

      Log.d(LOG_TAG, "POST to " + url);

      heer = new HttpPost(url);

      // Setting Entity if provided
      if (entity != null) {
        Log.d(LOG_TAG, "ENTITY PROVIDED");
        heer.setEntity(entity);
      }

      // Setting Headers if provided
      if (headers != null) {
        Log.d(LOG_TAG, "HEADERS PROVIDED");
        for (Header header : headers) {
          heer.setHeader(header);
        }
      }

      // Setting Credentials if provided
      if (credential != null) {
        Log.d(LOG_TAG, "CREDENTIAL PROVIDED : "
            + credential.getUserName() + ":"
            + credential.getPassword());
        httpClient.getCredentialsProvider().setCredentials(
            new AuthScope(AuthScope.ANY), credential);
      }

      // execute the request
      if (host != null) {
        response = httpClient.execute(host, (HttpPost) heer);
      } else {
        response = httpClient.execute((HttpPost) heer);
      }
    } else if (method == METHOD_PUT) {
      // ------------------ PUT
      response = httpClient.execute(new HttpPut(url));
    } else if (method == METHOD_DELETE) {
      // ------------------ DELETE
      response = httpClient.execute(new HttpDelete(url));
    } else {
      // ------------------ GET (DEFAULT: IF NOT POST, PUT, DELETE)
      response = httpClient.execute(new HttpGet(url));
    }

    Log.d(LOG_TAG, "StatusLine " + response.getStatusLine());

    // Setting the response entity
    entity = response.getEntity();

    // if entity is not null, then print it to the return value
    if (entity != null) {
      InputStream instream = entity.getContent();
      String result = convertStreamToString(instream);
      retval = result;
      instream.close();
    }

    // return it!
    return retval;
  }
  public static String convertStreamToString(InputStream is) {

    BufferedReader reader = new BufferedReader(new InputStreamReader(is));
    StringBuilder sb = new StringBuilder();

    String line = null;
    try {
      while ((line = reader.readLine()) != null) {
        sb.append(line + "\n");
      }
    } catch (IOException e) {
      e.printStackTrace();
    } finally {
      try {
        is.close();
      } catch (IOException e) {
        e.printStackTrace();
      }
    }
    return sb.toString();
  }

  public String getResult() {
    return result;
  }
}

Http Client Manager

    
//package com.filmatchs.utils;

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

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpDelete;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.methods.HttpPut;
import org.apache.http.impl.client.DefaultHttpClient; //
//import org.json.JSONArray;
//import org.json.JSONException;
//import org.json.JSONObject;

import android.util.Log;

public class HttpClientManager {

  public static final String TAG = "RestClient";

  public static final int METHOD_GET = 0;
  public static final int METHOD_POST = 1;
  public static final int METHOD_PUT = 2;
  public static final int METHOD_DELETE = 4;

  //private String postfix = "";
  private String result = null;

  public HttpClientManager(String url) throws IOException,
      ClientProtocolException {
    this.result = connectResponse(url);
  }

  public HttpClientManager(String url, int method) throws IOException,
      ClientProtocolException {
    this.result = connectResponse(url, method);
  }

  public HttpClientManager(String url, int method, String postfix)
      throws IOException, ClientProtocolException {
    this.result = connectResponse(url, method, postfix);
  }

  public String getResult() {
    return this.result;
  }

  private static String convertStreamToString(InputStream is) {

    BufferedReader reader = new BufferedReader(new InputStreamReader(is));
    StringBuilder sb = new StringBuilder();

    String line = null;
    try {
      while ((line = reader.readLine()) != null) {
        sb.append(line + "\n");
      }
    } catch (IOException e) {
      e.printStackTrace();
    } finally {
      try {
        is.close();
      } catch (IOException e) {
        e.printStackTrace();
      }
    }
    return sb.toString();
  }


  public static String connectResponse(String url) throws IOException,
      ClientProtocolException {
    return connectResponse(url, METHOD_GET, null);
  }


  public static String connectResponse(String url, int method)
      throws IOException, ClientProtocolException {
    return connectResponse(url, method, null);
  }

  public static String connectResponse(String url, int method, String postfix)
      throws IOException, ClientProtocolException {
    HttpClient httpClient = new DefaultHttpClient();

    if (postfix == null) {
      postfix = "";
    }

    String retval = "";

    url += postfix;

    HttpResponse response = null;

    if (method == METHOD_POST) {
      // -------------------------------- if POST
      response = httpClient.execute(new HttpPost(url));
    } else if (method == METHOD_PUT) {
      // -------------------------------- if PUT
      response = httpClient.execute(new HttpPut(url));
    } else if (method == METHOD_DELETE) {
      // -------------------------------- if DELETE
      response = httpClient.execute(new HttpDelete(url));
    } else {
      // -------------------------------- default GET
      response = httpClient.execute(new HttpGet(url));
    }

    Log.i(TAG, response.getStatusLine().toString());

    HttpEntity entity = response.getEntity();

    if (entity != null) {

      InputStream instream = entity.getContent();
      String result = convertStreamToString(instream);
      retval = result;
      instream.close();
    }

    return retval;
  }

}

Multipart Post

     
package app.test;

import java.io.ByteArrayInputStream;
import java.io.InputStream;

import org.apache.commons.io.IOUtils;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.mime.MultipartEntity;
import org.apache.http.entity.mime.content.InputStreamBody;
import org.apache.http.entity.mime.content.StringBody;
import org.apache.http.impl.client.DefaultHttpClient;

import android.app.Activity;

public class Test extends Activity
{
    public void executeMultipartPost()throws Exception
    {

        try {
            InputStream is = this.getAssets().open("data.xml");
            HttpClient httpClient = new DefaultHttpClient();
            HttpPost postRequest = 
             new HttpPost("http://192.178.10.131/WS2/Upload.aspx");

            byte[] data = IOUtils.toByteArray(is);

            InputStreamBody isb = new InputStreamBody(new ByteArrayInputStream(data),"uploadedFile");
            StringBody sb1 = new StringBody("asdf");
            StringBody sb2 = new StringBody("asdfasdf");

            MultipartEntity multipartContent = new MultipartEntity();
            multipartContent.addPart("uploadedFile", isb);
            multipartContent.addPart("one", sb1);
            multipartContent.addPart("two", sb2);

            postRequest.setEntity(multipartContent);
            HttpResponse res =httpClient.execute(postRequest);
            res.getEntity().getContent().close();
        } catch (Throwable e)
        {
            // handle exception here
         }
    }
}

Get Server Data

     
//package com.example.TestDB;

import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import android.app.Activity;
import android.os.Bundle;
import android.util.Log;
import android.widget.LinearLayout;
import android.widget.TextView;

public class TestDB extends Activity {
  /** Called when the activity is first created. */

  TextView txt;

  @Override
  public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    //setContentView(R.layout.main);
    // Create a crude view - this should really be set via the layout
    // resources
    // but since its an example saves declaring them in the XML.
    LinearLayout rootLayout = new LinearLayout(getApplicationContext());
    txt = new TextView(getApplicationContext());
    rootLayout.addView(txt);
    setContentView(rootLayout);

    // Set the text and call the connect function.
    txt.setText("Connecting...");
    // call the method to run the data retreival
    txt.setText(getServerData(KEY_121));

  }

  public static final String KEY_121 = "http://50.56.69.127/getAllPeopleBornAfter.php"; // i
                                              // use
                                              // my
                                              // real
                                              // ip
                                              // here

  private String getServerData(String returnString) {

    InputStream is = null;

    String result = "";
    // the year data to send
    ArrayList<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
    nameValuePairs.add(new BasicNameValuePair("year", "1965"));

    // http post
    try {
      HttpClient httpclient = new DefaultHttpClient();
      HttpPost httppost = new HttpPost(KEY_121);
      httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
      HttpResponse response = httpclient.execute(httppost);
      HttpEntity entity = response.getEntity();
      is = entity.getContent();

    } catch (Exception e) {
      Log.e("log_tag", "Error in http connection " + e.toString());
    }

    // convert response to string
    try {
      BufferedReader reader = new BufferedReader(new InputStreamReader(
          is, "iso-8859-1"), 8);
      StringBuilder sb = new StringBuilder();
      String line = null;
      while ((line = reader.readLine()) != null) {
        sb.append(line + "\n");
      }
      is.close();
      result = sb.toString();
    } catch (Exception e) {
      Log.e("log_tag", "Error converting result " + e.toString());
    }
    // parse json data
    try {
      JSONArray jArray = new JSONArray(result);
      for (int i = 0; i < jArray.length(); i++) {
        JSONObject json_data = jArray.getJSONObject(i);
        Log.i("log_tag",
            "id: " + json_data.getInt("id") + ", name: "
                + json_data.getString("name") + ", sex: "
                + json_data.getInt("sex") + ", birthyear: "
                + json_data.getInt("birthyear"));
        // Get an output to the screen
        returnString += "\n\t" + jArray.getJSONObject(i);
      }
    } catch (JSONException e) {
      Log.e("log_tag", "Error parsing data " + e.toString());
    }
    return returnString;
  }

}

Yahoo News Crawler

     
//package com.a4studio.android.util;

import java.io.IOException;
import java.io.Serializable;
import java.io.UnsupportedEncodingException;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.List;

import org.xmlpull.v1.XmlPullParser;
import org.xmlpull.v1.XmlPullParserException;

import android.util.Log;
import android.util.Xml;

public class YahooNewsCrawler {

  private final static String TAG=YahooNewsCrawler.class.getSimpleName();
  private String language = "en";
  private String keyword;
  private String site;
  private int    results;
  private String uri= "";    
  
  private final static String NEWS_SERVICE = "http://search.yahooapis.com/NewsSearchService/V1/newsSearch?";
  private final static String APP_ID = "iEjUXGrV34HmLcV9m1gm1OBUWUve.fUcYv553gw.MUHn5b8BA_8W8Fe4AxuOLMKKLLU-";
  
  private List<NewsItem> newsResults = new ArrayList<NewsItem>();
  
  public YahooNewsCrawler(String keyword,int results)
  {
    this.keyword = keyword;
    this.results = results;        
  }
  public void search()
  {
    XmlPullParser xmlPull = Xml.newPullParser();
    
    URL urlObj;
  
      try {
        keyword = URLEncoder.encode(keyword,"UTF-8");
        uri = NEWS_SERVICE+"appid="+APP_ID+"&"+
            "query="+keyword+"&"+"" +
            "results="+results+"&"+
            "language=en";
        
        Log.d(TAG,uri);
        urlObj = new URL(uri);
        URLConnection conn = urlObj.openConnection();
        
        xmlPull.setInput(conn.getInputStream(),"UTF-8");
        
        int eventCode = xmlPull.getEventType();
        
        NewsItem item = null;
        String name ;
        
        while(eventCode != XmlPullParser.END_DOCUMENT)
        {
        switch (eventCode) {
        case XmlPullParser.START_DOCUMENT:
          break;
        case XmlPullParser.START_TAG:
          name = xmlPull.getName();
          if (name.equalsIgnoreCase(NewsItem.RESULT)) {
            item = new NewsItem();
          } else if (item != null) {
            String text = xmlPull.nextText();
            if (name.equalsIgnoreCase(NewsItem.TITLE)) {
              item.setTitle(text);
            } else if (name.equalsIgnoreCase(NewsItem.SUMMARY)) {
              item.setSummary(text);
            } else if (name.equalsIgnoreCase(NewsItem.URL)) {
              item.setUrl(text);
            } else if (name.equalsIgnoreCase(NewsItem.CLICKURL)) {
              item.setClickUrl(text);
            } else if (name.equalsIgnoreCase(NewsItem.NEWSSOURCE)) {
              item.setNewsSource(text);
            } else if (name.equalsIgnoreCase(NewsItem.NEWSSOURCEURL)) {
              item.setNewsSrouceUrl(text);
            } else if (name.equalsIgnoreCase(NewsItem.LANGUAGE)) {
              item.setLanguage(text);
            } else if (name.equalsIgnoreCase(NewsItem.PUBLISHDATE)) {
              item.setPublishDate(Long.parseLong(text));
            } else if (name.equalsIgnoreCase(NewsItem.MODIFICATIONDATE)) {
              item.setModifDate(Long.parseLong(text));
            }
          }
          break;
        case XmlPullParser.END_TAG:
          if(item != null && xmlPull.getName().equalsIgnoreCase(NewsItem.RESULT))
          {
            newsResults.add(item);
            item = null;
          }
          break;
        default:
          break;
            
        }
        
        eventCode = xmlPull.next();
      }
      } catch (UnsupportedEncodingException e) {
        // TODO Auto-generated catch block
        Log.e(TAG, "search", e);
      } catch (MalformedURLException e) {
        // TODO Auto-generated catch block
        Log.e(TAG, "search", e);
      } catch (IOException e) {
        // TODO Auto-generated catch block
        Log.e(TAG, "search", e);
      } catch (XmlPullParserException e) {
        // TODO Auto-generated catch block
        Log.e(TAG, "search", e);
      }


  }
  

  /**
   * @return the newsResults
   */
  public List<NewsItem> getNewsResults() {
    return newsResults;
  }

  /**
   * @param args
   */
  public static void main(String[] args) {
    // TODO Auto-generated method stub
    YahooNewsCrawler crawler = new YahooNewsCrawler("nokia siemens network",1);
    crawler.search();
    
    List<NewsItem> items = crawler.getNewsResults();
    
    for(NewsItem item : items)
    {
      System.out.println("->"+item);
    }
  }

}

class NewsItem implements Serializable{

  /**
   * 
   */
  private static final long serialVersionUID = 1L;
  
  public final static String RESULT = "Result";
  public final static String TITLE = "Title";
  public final static String SUMMARY = "Summary";
  public final static String URL = "Url";
  public final static String CLICKURL = "ClickUrl";
  public final static String NEWSSOURCE = "NewsSource";
  public final static String NEWSSOURCEURL = "NewsSourceUrl";
  public final static String LANGUAGE = "Language";
  public final static String PUBLISHDATE = "PublishDate";
  public final static String MODIFICATIONDATE = "ModificationDate";

  private String title;
  private String summary;
  private String url;
  private String clickUrl;
  private String newsSource;
  private String newsSrouceUrl;
  private String language;
  private long publishDate;
  private long modifDate;
  
  private String content;

  /**
   * @return the title
   */
  public String getTitle() {
    return title;
  }

  /**
   * @param title
   *            the title to set
   */
  public void setTitle(String title) {
    this.title = title;
  }

  /**
   * @return the summary
   */
  public String getSummary() {
    return summary;
  }

  /**
   * @param summary
   *            the summary to set
   */
  public void setSummary(String summary) {
    this.summary = summary;
  }

  /**
   * @return the url
   */
  public String getUrl() {
    return url;
  }

  /**
   * @param url
   *            the url to set
   */
  public void setUrl(String url) {
    this.url = url;
  }

  /**
   * @return the clickUrl
   */
  public String getClickUrl() {
    return clickUrl;
  }

  /**
   * @param clickUrl
   *            the clickUrl to set
   */
  public void setClickUrl(String clickUrl) {
    this.clickUrl = clickUrl;
  }

  /**
   * @return the newsSource
   */
  public String getNewsSource() {
    return newsSource;
  }

  /**
   * @param newsSource
   *            the newsSource to set
   */
  public void setNewsSource(String newsSource) {
    this.newsSource = newsSource;
  }

  /**
   * @return the newsSrouceUrl
   */
  public String getNewsSrouceUrl() {
    return newsSrouceUrl;
  }

  /**
   * @param newsSrouceUrl
   *            the newsSrouceUrl to set
   */
  public void setNewsSrouceUrl(String newsSrouceUrl) {
    this.newsSrouceUrl = newsSrouceUrl;
  }

  /**
   * @return the language
   */
  public String getLanguage() {
    return language;
  }

  /**
   * @param language
   *            the language to set
   */
  public void setLanguage(String language) {
    this.language = language;
  }

  /**
   * @return the publishDate
   */
  public long getPublishDate() {
    return publishDate;
  }

  /**
   * @param publishDate
   *            the publishDate to set
   */
  public void setPublishDate(long publishDate) {
    this.publishDate = publishDate;
  }

  /**
   * @return the modifDate
   */
  public long getModifDate() {
    return modifDate;
  }

  /**
   * @param modifDate
   *            the modifDate to set
   */
  public void setModifDate(long modifDate) {
    this.modifDate = modifDate;
  }

  
  /**
   * @return the content
   */
  public String getContent() {
    return content;
  }

  /**
   * @param content the content to set
   */
  public void setContent(String content) {
    this.content = content;
  }

  /* (non-Javadoc)
   * @see java.lang.Object#toString()
   */
  @Override
  public String toString() {
    // TODO Auto-generated method stub
    return this.title+"\n"+
    this.summary +"\n"+
    this.url+"\n"+
    this.clickUrl+"\n"+
    this.newsSource+"\n"+
    this.newsSrouceUrl+"\n"+
    this.language+"\n"+
    this.publishDate+"\n"+
    this.modifDate+"\n";
  }

  /**
   * @param args
   */
  public static void main(String[] args) {
    // TODO Auto-generated method stub

  }

}

Send Packet

//package com.mediaportal.ampdroid.utils;

import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;

import android.util.Log;

public class WakeOnLan {
   public static Boolean sendMagicPacket(String _mac, String _ip, int _port) {
      try {
         byte[] macBytes = getMacBytes(_mac);
         byte[] bytes = new byte[6 + 16 * macBytes.length];
         for (int i = 0; i < 6; i++) {
            bytes[i] = (byte) 0xff;
         }
         for (int i = 6; i < bytes.length; i += macBytes.length) {
            System.arraycopy(macBytes, 0, bytes, i, macBytes.length);
         }

         InetAddress address = InetAddress.getByName(_ip);
         DatagramPacket packet = new DatagramPacket(bytes, bytes.length, address, _port);
         DatagramSocket socket = new DatagramSocket();
         socket.send(packet);
         socket.close();
         return true;
      } catch (Exception e) {
         return false;
      }
   }

   public static Boolean sendMagicPacket(String _mac, int _port) {
      return sendMagicPacket(_mac, "255.255.255.255", _port);
   }

   public static Boolean sendMagicPacket(String _mac) {
      return sendMagicPacket(_mac, "255.255.255.255", 9);
   }

   private static byte[] getMacBytes(String macStr) throws IllegalArgumentException {
      byte[] bytes = new byte[6];
      String[] hex = macStr.split("(\\:|\\-)");
      if (hex.length != 6) {
         throw new IllegalArgumentException("Invalid MAC address.");
      }
      try {
         for (int i = 0; i < 6; i++) {
            bytes[i] = (byte) Integer.parseInt(hex[i], 16);
         }
      } catch (NumberFormatException e) {
         throw new IllegalArgumentException("Invalid hex digit in MAC address.");
      }
      return bytes;
   }
}

Read a web page

//package org.snancekivell.one_day_watcher;

import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.URL;
import java.util.LinkedList;

public class site_utils {
    public static final String ADDRESS_1_DAY = "http://www.1-day.co.nz/";
    public static LinkedList<String> getpage(){
        LinkedList<String> page = new LinkedList<String>();

        try{
            URL url = new URL(ADDRESS_1_DAY);

            InputStream is =url.openStream();

            BufferedReader reader = new BufferedReader(new InputStreamReader(is));

            String line;
            while ((line=reader.readLine())!=null){
                page.add(line);
            }
        }
        catch(Exception e){
            e.printStackTrace();
            System.exit(1);
        }

        return page;
    }

    public static LinkedList<String> get_products(LinkedList<String> page) {
        LinkedList<String> products= new LinkedList<String>();

        for (int i=0; i< page.size();i++){
            if (page.get(i).contains("<div class=\"productTitle\">"))
            {
                i+=2;
                String head1= page.get(i).trim().replace("</h1>", "");
                i+=2;
                String head2 = page.get(i).trim().replace("</h2>", "");
                i+=16;
                String price = page.get(i).replace("<li class=\"amount\">", "").replace("</li>", "").trim();

                products.add(head1+" : "+head2+" : "+price);

            }
        }

        return products;
    }
}


parse Request Header

     

//package jp.tf_web.httpserversample.http;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.StringReader;
import java.util.HashMap;

import org.apache.http.Header;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.ProtocolVersion;
import org.apache.http.RequestLine;
import org.apache.http.StatusLine;
import org.apache.http.entity.BasicHttpEntity;
import org.apache.http.entity.ByteArrayEntity;
import org.apache.http.message.BasicHttpResponse;
import org.apache.http.message.BasicLineParser;
import org.apache.http.message.BufferedHeader;
import org.apache.http.util.CharArrayBuffer;

import android.util.Log;
import android.webkit.MimeTypeMap;

class HttpUtil {
  public final static String HTTP_PROTOCOL = "HTTP/1.1";
  public final static String HEADER_NAME_REQUESTLINE = "RequestLine";
  public final static String HEADER_NAME_CONTENT_LENGTH = "Content-Length";
  
  private HttpUtil(){}
  
  //??????????????
  public static HashMap<String,Object> parseRequestHeader(String headers_str) throws IOException{
    //????????
    StringReader sr = new StringReader(headers_str);
    BufferedReader bur = new BufferedReader(sr);

    HashMap<String,Object> headerList = new HashMap<String,Object>();
    String line;
    int line_index = 0;
    while((line = bur.readLine()) != null){
      if(line.length() == 0) break;
      
      //????????
      if(line_index == 0){
        //????????
        BasicLineParser parser = new BasicLineParser();
        RequestLine request_line = BasicLineParser.parseRequestLine(line, parser);
        headerList.put(HttpUtil.HEADER_NAME_REQUESTLINE,request_line);
      }
      else{
        //????
        CharArrayBuffer cab = new CharArrayBuffer(line.length());
        cab.append(line);
        Header h = new BufferedHeader(cab);
        headerList.put(h.getName(),h);
      }
      
      line_index++;
    }
    bur.close();
    sr.close();
    
    return headerList;
  }
  
  //???????????
  public static StatusLine createStatusLine(int status,String reason){
    BasicLineParser parser = new BasicLineParser();
    return BasicLineParser.parseStatusLine(HTTP_PROTOCOL+" "+status+" "+reason,parser);
  }
  
  //HTTP????????
  public static HttpResponse createHttpResponse(int status,String reason,HttpEntity entity){
    StatusLine header_sl = HttpUtil.createStatusLine(status,reason);
    HttpResponse hr = new BasicHttpResponse(header_sl);
    hr.setEntity(entity);    
    return hr; 
  }
  
  public static HttpEntity createHttpEntity(String contentType,byte[] entity_buf){
    ByteArrayEntity he = new ByteArrayEntity(entity_buf);
    he.setContentType(contentType);
    return he;
  }
  
  public static String getMimeTypeFromUri(String uri){
    //?????MimeType???
    String ext = MimeTypeMap.getSingleton().getFileExtensionFromUrl(uri);
    String mimeType = MimeTypeMap.getSingleton().getMimeTypeFromExtension(ext);
    
    //????? "application/octet-stream"
    //ToDo mime-type????????????mime-type???????????????
    mimeType = (mimeType != null)?mimeType:"application/octet-stream";
    Log.d(HttpUtil.class.getName(),"ext:"+ext+" mimeType:"+mimeType);

    return mimeType;
  }
}

   

Data Send Utils

     
import java.io.DataOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.LinkedList;
import java.util.List;

import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.protocol.HTTP;

import android.util.Base64;
import android.util.Log;

/**
 * Send Data Utils
 * 
 * @author wpc
 * 
 */
public class DataSendUtils {

  public static boolean httpPost(String pathToOurFile, String urlServer,
      String formName) {

    HttpURLConnection connection = null;
    DataOutputStream outputStream = null;

    String lineEnd = "\r\n";
    String twoHyphens = "--";
    String boundary = "*****";

    int bytesRead, bytesAvailable, bufferSize;
    byte[] buffer;
    int maxBufferSize = 1 * 1024 * 1024;

    boolean sendSuccess = true;

    try {
      FileInputStream fileInputStream = new FileInputStream(new File(
          pathToOurFile));

      URL url = new URL(urlServer);
      connection = (HttpURLConnection) url.openConnection();

      // Allow Inputs & Outputs
      connection.setDoInput(true);
      connection.setDoOutput(true);
      connection.setUseCaches(false);

      // Enable POST method
      connection.setRequestMethod("POST");

      connection.setRequestProperty("Connection", "Keep-Alive");
      connection.setRequestProperty("Content-Type",
          "multipart/form-data;boundary=" + boundary);

      outputStream = new DataOutputStream(connection.getOutputStream());
      outputStream.writeBytes(twoHyphens + boundary + lineEnd);
      outputStream.flush();
      outputStream.writeBytes("Content-Disposition: form-data; name=\""
          + formName + "\";filename=\"" + pathToOurFile + "\""
          + lineEnd);
      outputStream.flush();
      outputStream.writeBytes(lineEnd);
      outputStream.flush();

      bytesAvailable = fileInputStream.available();
      bufferSize = Math.min(bytesAvailable, maxBufferSize);
      buffer = new byte[bufferSize];

      // Read file
      bytesRead = fileInputStream.read(buffer, 0, bufferSize);

      while (bytesRead > 0) {
        outputStream.write(buffer, 0, bufferSize);
        outputStream.flush();
        bytesAvailable = fileInputStream.available();
        bufferSize = Math.min(bytesAvailable, maxBufferSize);
        bytesRead = fileInputStream.read(buffer, 0, bufferSize);
      }

      outputStream.writeBytes(lineEnd);
      outputStream.flush();
      outputStream.writeBytes(twoHyphens + boundary + twoHyphens
          + lineEnd);
      outputStream.flush();
      fileInputStream.close();
      outputStream.close();

      connection.getResponseCode();
      connection.getResponseMessage();

    } catch (Exception ex) {
      sendSuccess = false;
    } finally {
      connection.disconnect();
    }
    return sendSuccess;
  }

  /**
   * TODO FIX Check the file length, it's long not int.This may lead the
   * problem.
   * 
   * @param fileName
   * @param url
   * @return
   */
  public static boolean httpPostBase64(String fileName, String url,
      String formKey, String inputName) {
    try {
      File file = new File(fileName);
      FileInputStream in = new FileInputStream(file);
      byte[] buffer = new byte[(int) file.length() + 100];
      int length = in.read(buffer);
      String data = Base64.encodeToString(buffer, 0, length,Base64.DEFAULT);

      HttpPost httpRequest = new HttpPost(url);
      List<NameValuePair> params = new LinkedList<NameValuePair>();
      params.add(new BasicNameValuePair("hl", "en_GB"));
      params.add(new BasicNameValuePair("formkey", formKey));
      params.add(new BasicNameValuePair(inputName, data));
      httpRequest.setEntity(new UrlEncodedFormEntity(params, HTTP.UTF_8));
      HttpResponse httpResponse = new DefaultHttpClient()
          .execute(httpRequest);
      if (httpResponse.getStatusLine().getStatusCode() != 200) {
        Log.d("HTTP Response:", url);
        Log.d("HTTP Response Code", httpResponse.getStatusLine()
            .toString());
        return false;
      }
    } catch (Exception e) {
      return false;
    }
    return true;
  }
}

This class is in charge of synchronizing the events (with due dates) with Google Calendar

     



import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLEncoder;

import javax.net.ssl.HostnameVerifier;
import javax.net.ssl.HttpsURLConnection;
import javax.net.ssl.SSLSession;
import javax.xml.parsers.SAXParser;
import javax.xml.parsers.SAXParserFactory;

import org.xml.sax.Attributes;
import org.xml.sax.InputSource;
import org.xml.sax.SAXException;
import org.xml.sax.XMLReader;
import org.xml.sax.helpers.DefaultHandler;

class CalendarsHandler extends DefaultHandler {
  // Fields
  private boolean titleTag = false; // For the <title> tag.
  private boolean entryTag = false; // <entry> tag.

  private ParsedCalendarsDataSet myParsedCalendarsDataSet = new ParsedCalendarsDataSet();

  // Getter & Setter
  public ParsedCalendarsDataSet getParsedData() {
    return this.myParsedCalendarsDataSet;
  }

  @Override
  public void startDocument() throws SAXException {
    this.myParsedCalendarsDataSet = new ParsedCalendarsDataSet();
  }

  @Override
  public void endDocument() throws SAXException {
    // Nothing to do
  }

  /**
   * Gets be called on opening tags like: <tag> Can provide attribute(s), when
   * xml was like: <tag attribute="attributeValue">
   */
  @Override
  public void startElement(String namespaceURI, String localName,
      String qName, Attributes atts) throws SAXException {
    if (localName.equals("title")) {
      this.titleTag = true;
    } else if (localName.equals("entry")) {
      this.entryTag = true;
    }

  }

  /**
   * Gets be called on closing tags like: </tag>
   */
  @Override
  public void endElement(String namespaceURI, String localName, String qName)
      throws SAXException {
    if (localName.equals("title")) {
      this.titleTag = false;
    } else if (localName.equals("entry")) {
      this.entryTag = false;
    }
  }

  /**
   * Gets be called on the following structure: <tag>characters</tag>
   */
  @Override
  public void characters(char ch[], int start, int length) {
    if (this.entryTag && this.titleTag) {
      myParsedCalendarsDataSet.setExtractedString(new String(ch, start,
          length));
    }
  }
}

class ParsedCalendarsDataSet {
  private String extractedString = "";

  public String getExtractedString() {
    return extractedString;
  }

  public void setExtractedString(String extractedString) {
    this.extractedString = this.extractedString + extractedString + "\n";
  }

  public String toString() {
    return this.extractedString;
  }
}

// For creating a single calendar event see:
// http://code.google.com/apis/calendar/docs/2.0/developers_guide_protocol.html#CreatingSingle

/**
 * This class is in charge of synchronizing the events (with due dates) with
 * Google Calendar
 */
public final class GoogleCalendar {
  private static String mAuthToken = null;
  private static String mUsername = "", mPassword = "";
  private static long mLastActivity = 0;
  private final static HostnameVerifier HOSTNAME_VERIFIER = new HostnameVerifier() {
    public boolean verify(String hostname, SSLSession session) {
      return "www.google.com".equals(hostname);
    }
  };

  /**
   * The login has to be set by someone, either in a configuration window, or
   * in the main view, on creation, etc.
   * 
   * @param username
   * @param password
   */
  public final static void setLogin(String username, String password) {
    mUsername = username;
    mPassword = password;
  }

  /**
   * Initiates the proper communications with Google to add an event in the
   * user's main calendar
   * 
   * @param title
   *            Name of the task and future event
   * @param year
   * @param month
   * @param day
   * @param hour
   *            (if hour is -1, the event will last all day)
   * @param minute
   * @return true if the event was created
   * @throws Exception
   */
  public final static boolean createEvent(String title, int year, int month,
      int day, int hour, int minute) throws Exception {

    authenticate(false);
    int hour_end = hour + 1; // Default to 1 hour duration.
    boolean redirect = false;
    month++; // our months are from 0 to 11
    String sessionUrl = "http://www.google.com/calendar/feeds/default/private/full";
    do {
      HttpURLConnection uc = (HttpURLConnection) new URL(sessionUrl)
          .openConnection();
      uc.setDoOutput(true);
      uc.setUseCaches(false);
      uc.setRequestMethod("POST");
      uc.setRequestProperty("Content-Type", "application/atom+xml");
      uc.setRequestProperty("Authorization", "GoogleLogin auth="
          + mAuthToken);
      BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(
          uc.getOutputStream()));
      String s = year + "-" + (month / 10 < 1 ? "0" + month : month)
          + "-" + (day / 10 < 1 ? "0" + day : day);
      bw.write("<entry xmlns='http://www.w3.org/2005/Atom' xmlns:gd='http://schemas.google.com/g/2005'>\n<category scheme='http://schemas.google.com/g/2005#kind' term='http://schemas.google.com/g/2005#event'></category>\n"
          + "<title type='text'>"
          + title.replace('\'', '"')
          + "</title>\n"
          + "<content type='text'>Event created with Acaletto on an Android phone.</content>\n"
          + "<gd:transparency value='http://schemas.google.com/g/2005#event.opaque'></gd:transparency>\n<gd:eventStatus value='http://schemas.google.com/g/2005#event.confirmed'></gd:eventStatus>\n"
          + "<gd:when startTime='"
          + s
          + (hour != -1 ? "T" + (hour / 10 < 1 ? "0" + hour : hour)
              + ":" + (minute / 10 < 1 ? "0" + minute : minute)
              + ":00.000Z' endTime='" + s + "T"
              + (hour_end / 10 < 1 ? "0" + hour_end : hour_end)
              + ":" + (minute / 10 < 1 ? "0" + minute : minute)
              + ":00.000Z" : "") + "'></gd:when>\n</entry>");
      bw.flush();
      bw.close();
      if (!(redirect) && uc.getResponseCode() == 302) { // REDIRECT
        redirect = true;
        sessionUrl = uc.getHeaderField("Location");
      } else {
        redirect = false;
        if (uc.getResponseCode() == HttpURLConnection.HTTP_CREATED) {
          return true;
        }
      }
    } while (redirect);
    return false;
  }

  /**
   * Get all the calendars the user owns (i.e. is allowed to change).
   * 
   * @return String with calendars
   * @throws Exception
   */
  public final static String ownCalendars() throws Exception {
    URL gcal = new URL(
        "http://www.google.com/calendar/feeds/default/owncalendars/full");
    HttpURLConnection uc = (HttpURLConnection) gcal.openConnection();
    uc.setDoOutput(true);
    uc.setUseCaches(false);
    uc.setRequestMethod("GET");
    uc.setRequestProperty("Content-Type", "application/xml");
    uc.setRequestProperty("Authorization", "GoogleLogin auth=" + mAuthToken);

    /* Get a SAXParser from the SAXPArserFactory. */
    SAXParserFactory spf = SAXParserFactory.newInstance();
    SAXParser sp = spf.newSAXParser();

    /* Get the XMLReader of the SAXParser we created. */
    XMLReader xr = sp.getXMLReader();
    /* Create a new ContentHandler and apply it to the XML-Reader */
    CalendarsHandler myCalendarsHandler = new CalendarsHandler();
    xr.setContentHandler(myCalendarsHandler);

    /* Parse the xml-data from our URL. */
    xr.parse(new InputSource(uc.getInputStream()));
    /* Parsing has finished. */

    ParsedCalendarsDataSet parsedCalendarsDataSet = myCalendarsHandler
        .getParsedData();

    return parsedCalendarsDataSet.toString();
  }

  /**
   * Authentication in the Google Calendar service through HTTPS
   * 
   * @param force
   *            - if true, it forces a re-authentication, even if the present
   *            session isn't timeout
   * @return true if authentication succeeds
   * @throws Exception
   */
  public final static boolean authenticate(boolean force) throws Exception {

    long millis = System.currentTimeMillis();
    if (!(force) && millis - mLastActivity < 1800000) {
      mLastActivity = millis;
      return true;
    } else {
      mLastActivity = millis;
    }

    HttpsURLConnection uc = (HttpsURLConnection) new URL(
        "https://www.google.com/accounts/ClientLogin").openConnection();
    uc.setHostnameVerifier(HOSTNAME_VERIFIER);
    uc.setDoOutput(true);
    uc.setRequestMethod("POST");
    uc.setRequestProperty("Content-Type",
        "application/x-www-form-urlencoded");
    uc.setUseCaches(false);
    BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(
        uc.getOutputStream()));
    bw.write(URLEncoder.encode("Email", "UTF-8") + "="
        + URLEncoder.encode(mUsername, "UTF-8") + "&"
        + URLEncoder.encode("Passwd", "UTF-8") + "="
        + URLEncoder.encode(mPassword, "UTF-8") + "&"
        + URLEncoder.encode("source", "UTF-8") + "="
        + URLEncoder.encode("Acaletto", "UTF-8") + "&"
        + URLEncoder.encode("service", "UTF-8") + "="
        + URLEncoder.encode("cl", "UTF-8"));
    bw.flush();
    bw.close();
    BufferedReader in = new BufferedReader(new InputStreamReader(
        uc.getInputStream()));
    if (uc.getResponseCode() == HttpsURLConnection.HTTP_FORBIDDEN) {
      in.close();
      return false;
    }
    // only the 3rd parameter (Auth) is of interest
    in.readLine();
    in.readLine();
    mAuthToken = in.readLine().substring(5);
    in.close();
    return true;
  }
}

Update Favicon

     

//package com.dreamcode.anfeedreader.utils;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;

import android.content.Context;

class Main {
  public byte[] updateFavicon(Context ctx, String iconUrl)
      throws MalformedURLException {
    try {
      return loadBytesFromURL(ctx, new URL(iconUrl));
    } catch (IOException e) {
      // TODO Auto-generated catch block
      e.printStackTrace();
    }
    return null;
  }

  public byte[] loadBytesFromURL(Context ctxU, URL url) throws IOException {
    byte[] b = null;
    URLConnection con = url.openConnection();
    int size = con.getContentLength();
    InputStream in = null;

    try {
      if ((in = con.getInputStream()) != null)
        b = (size != -1) ? loadBytesFromStreamForSize(in, size)
            : loadBytesFromStream(in);
    } finally {
      if (in != null)
        try {
          in.close();
        } catch (IOException ioe) {
        }
    }
    return b;
  }

  public byte[] loadBytesFromStream(InputStream in) throws IOException {
    return loadBytesFromStream(in, kDEFAULT_CHUNK_SIZE);
  }

  public byte[] loadBytesFromStreamForSize(InputStream in, int size)
      throws IOException {
    int count, index = 0;
    byte[] b = new byte[size];

    // read in the bytes from input stream
    while ((count = in.read(b, index, size)) > 0) {
      size -= count;
      index += count;
    }
    return b;
  }
  private static int kDEFAULT_CHUNK_SIZE = 256;
  public byte[] loadBytesFromStream(InputStream in, int chunkSize)
      throws IOException {
    if (chunkSize < 1)
      chunkSize = kDEFAULT_CHUNK_SIZE;

    int count;
    ByteArrayOutputStream bo = new ByteArrayOutputStream();
    byte[] b = new byte[chunkSize];
    try {
      while ((count = in.read(b, 0, chunkSize)) > 0)
        bo.write(b, 0, count);
      byte[] thebytes = bo.toByteArray();
      return thebytes;
    } finally {
      bo.close();
      bo = null;
    }
  }
}

Converts key-value pair to appropriate signature for Facebook

//package fb4java.util;

import java.net.URI;
import java.net.URISyntaxException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.Map.Entry;

import org.apache.http.NameValuePair;
import org.apache.http.client.utils.URIUtils;
import org.apache.http.client.utils.URLEncodedUtils;
import org.apache.http.message.BasicNameValuePair;


 class Utility {
  private final static String HASHING_METHOD = "MD5";

  private static final String DEFAULT_CHARSET = "UTF-8";


  public static String convetToSignature(Map<String, String> keyVal,
      String apiSecret) {

    if (keyVal == null || apiSecret == null || keyVal.size() <= 0
        || apiSecret.trim().equals("")) {
      throw new IllegalArgumentException(
          "keyVal or api secret is not valid. Please Check it again.");
    }

    Iterator<Entry<String, String>> iterator = keyVal.entrySet().iterator();
    StringBuffer rslt = new StringBuffer();
    byte[] signature = null;

    while (iterator.hasNext()) {
      Entry<String, String> entry = iterator.next();
      rslt.append(entry.getKey());
      rslt.append("=");
      rslt.append(entry.getValue());
    }
    rslt.append(apiSecret);

    // convert sig to md5 hash
    try {
      MessageDigest md5 = MessageDigest.getInstance(HASHING_METHOD);
      md5.reset();
      md5.update(rslt.toString().getBytes());
      rslt.delete(0, rslt.length());

      signature = md5.digest();

      for (int i = 0; i < signature.length; i++) {
        String hex = Integer.toHexString(0xff & signature[i]);
        if (hex.length() == 1) {
          rslt.append('0');
        }
        rslt.append(hex);
      }

    } catch (NoSuchAlgorithmException e) {
      e.printStackTrace();
    }

    return rslt.toString();
  }


  public static URI createURI(Map<String, String> keyVal, String protocol,
      String server, String rscURL, String signature, String charset)
      throws URISyntaxException {
    URI rslt = null;

    if (keyVal == null || keyVal.size() <= 0) {
      throw new IllegalArgumentException(
          "keyVal is invalid. Please provide with proper key value.");
    }

    if (charset == null || charset.equals("")) {
      charset = DEFAULT_CHARSET;
    }

    List<NameValuePair> qparams = new ArrayList<NameValuePair>();
    Set<String> keys = keyVal.keySet();

    for (String key : keys) {
      qparams.add(new BasicNameValuePair(key, keyVal.get(key)));
    }
    // adds signature in url parameter
    qparams.add(new BasicNameValuePair("sig", signature.toLowerCase()));

    rslt = URIUtils.createURI(protocol, server, -1, rscURL, URLEncodedUtils
        .format(qparams, charset), null);

    return rslt;
  }
}