Returns an HttpURLConnection using sensible default settings for mobile and taking care of buggy behavior prior to Froyo. - Android Network

Android examples for Network:Network Connection

Description

Returns an HttpURLConnection using sensible default settings for mobile and taking care of buggy behavior prior to Froyo.

Demo Code

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

import android.os.Build;

public class Main {

  public static HttpURLConnection buildHttpUrlConnection(String urlString) throws MalformedURLException, IOException {
    disableConnectionReuseIfNecessary();

    URL url = new URL(urlString);

    HttpURLConnection conn = (HttpURLConnection) url.openConnection();
    conn.setReadTimeout(10000 /* milliseconds */);
    conn.setConnectTimeout(15000 /* milliseconds */);
    conn.setDoInput(true);/*from   w ww.jav a 2 s .c  o m*/
    conn.setRequestMethod("GET");
    return conn;
  }


  public static void disableConnectionReuseIfNecessary() {
    if (!isFroyoOrHigher()) {
      System.setProperty("http.keepAlive", "false");
    }
  }

  public static boolean isFroyoOrHigher() {
    return Build.VERSION.SDK_INT >= Build.VERSION_CODES.FROYO;
  }
}

Related Tutorials