Code example for HttpURLConnection

Methods: connect, disconnect, getResponseCode, setRequestProperty

1
    URLConnection conn = url.openConnection();
    if (!(conn instanceof HttpURLConnection)) {
      throw new IOException();
    } 
    HttpURLConnection connection = (HttpURLConnection) conn;
    connection.setRequestProperty("Accept", contentTypes);
    connection.setRequestProperty("Accept-Charset", "utf-8,*");
    connection.setRequestProperty("User-Agent", "ZXing (Android)");
    try { 
      try { 
        connection.connect();
      } catch (NullPointerException npe) {
        // this is an Android bug: http://code.google.com/p/android/issues/detail?id=16895 
        Log.w(TAG, "Bad URI? " + uri);
        throw new IOException(npe);
      } catch (IllegalArgumentException iae) {
        // Also seen this in the wild, not sure what to make of it. Probably a bad URL 
        Log.w(TAG, "Bad URI? " + uri);
        throw new IOException(iae);
      } 
      int responseCode;
      try { 
        responseCode = connection.getResponseCode();
      } catch (NullPointerException npe) {
        // this is maybe this Android bug: http://code.google.com/p/android/issues/detail?id=15554 
        Log.w(TAG, "Bad URI? " + uri);
        throw new IOException(npe);
      } 
      if (responseCode != HttpURLConnection.HTTP_OK) {
        throw new IOException("Bad HTTP response: " + responseCode);
      } 
      Log.i(TAG, "Consuming " + uri);
      return consume(connection, maxChars);
    } finally { 
      connection.disconnect();
    } 
  } 
 
  private static String getEncoding(URLConnection connection) {
    String contentTypeHeader = connection.getHeaderField("Content-Type");