public static BasicHttpParams defaultParams(int timeout) {
   BasicHttpParams httpClientParams = new BasicHttpParams();
   // connection to server timeouts
   HttpConnectionParams.setConnectionTimeout(httpClientParams, timeout);
   HttpConnectionParams.setSoTimeout(httpClientParams, timeout);
   // set to rfc 2109 as it puts the ASP (IIS) cookie _FIRST_, this is critical for interealty
   httpClientParams.setParameter(ClientPNames.COOKIE_POLICY, CookiePolicy.RFC_2109);
   return httpClientParams;
 }
  private static HttpClient setupHttpClient(boolean gzip) {
    SSLSocketFactory.getSocketFactory()
        .setHostnameVerifier(SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);
    SchemeRegistry schemeRegistry = new SchemeRegistry();
    schemeRegistry.register(new Scheme("http", PlainSocketFactory.getSocketFactory(), 80));
    schemeRegistry.register(new Scheme("https", SSLSocketFactory.getSocketFactory(), 443));
    BasicHttpParams params = new BasicHttpParams();
    params.setParameter(ConnManagerPNames.MAX_CONNECTIONS_PER_ROUTE, new ConnPerRouteBean(20));
    params.setIntParameter(ConnManagerPNames.MAX_TOTAL_CONNECTIONS, 200);
    ThreadSafeClientConnManager cm = new ThreadSafeClientConnManager(params, schemeRegistry);

    DefaultHttpClient httpClient = new DefaultHttpClient(cm, new BasicHttpParams());
    httpClient.setHttpRequestRetryHandler(
        new DefaultHttpRequestRetryHandler(HTTP_RETRY_COUNT, true));

    if (gzip) {
      httpClient.addRequestInterceptor(
          new HttpRequestInterceptor() {
            public void process(HttpRequest request, HttpContext context)
                throws HttpException, IOException {
              if (!request.containsHeader("Accept-Encoding")) {
                request.addHeader("Accept-Encoding", "gzip");
              }
            }
          });

      httpClient.addResponseInterceptor(
          new HttpResponseInterceptor() {
            public void process(HttpResponse response, HttpContext context)
                throws HttpException, IOException {
              HttpEntity entity = response.getEntity();
              Header ceheader = entity.getContentEncoding();
              if (ceheader != null) {
                HeaderElement[] codecs = ceheader.getElements();
                for (int i = 0; i < codecs.length; i++) {
                  if (codecs[i].getName().equalsIgnoreCase("gzip")) {
                    response.setEntity(new GzipDecompressingEntity(response.getEntity()));
                    return;
                  }
                }
              }
            }
          });
    }

    return httpClient;
  }
  /**
   * Opens the connection to a http server or proxy.
   *
   * @return the opened low level connection
   * @throws IOException if the connection fails for any reason.
   */
  @Override
  AndroidHttpClientConnection openConnection(Request req) throws IOException {
    SSLSocket sslSock = null;

    if (mProxyHost != null) {
      // If we have a proxy set, we first send a CONNECT request
      // to the proxy; if the proxy returns 200 OK, we negotiate
      // a secure connection to the target server via the proxy.
      // If the request fails, we drop it, but provide the event
      // handler with the response status and headers. The event
      // handler is then responsible for cancelling the load or
      // issueing a new request.
      AndroidHttpClientConnection proxyConnection = null;
      Socket proxySock = null;
      try {
        proxySock = new Socket(mProxyHost.getHostName(), mProxyHost.getPort());

        proxySock.setSoTimeout(60 * 1000);

        proxyConnection = new AndroidHttpClientConnection();
        HttpParams params = new BasicHttpParams();
        HttpConnectionParams.setSocketBufferSize(params, 8192);

        proxyConnection.bind(proxySock, params);
      } catch (IOException e) {
        if (proxyConnection != null) {
          proxyConnection.close();
        }

        String errorMessage = e.getMessage();
        if (errorMessage == null) {
          errorMessage = "failed to establish a connection to the proxy";
        }

        throw new IOException(errorMessage);
      }

      StatusLine statusLine = null;
      int statusCode = 0;
      Headers headers = new Headers();
      try {
        BasicHttpRequest proxyReq = new BasicHttpRequest("CONNECT", mHost.toHostString());

        // add all 'proxy' headers from the original request, we also need
        // to add 'host' header unless we want proxy to answer us with a
        // 400 Bad Request
        for (Header h : req.mHttpRequest.getAllHeaders()) {
          String headerName = h.getName().toLowerCase(Locale.ROOT);
          if (headerName.startsWith("proxy")
              || headerName.equals("keep-alive")
              || headerName.equals("host")) {
            proxyReq.addHeader(h);
          }
        }

        proxyConnection.sendRequestHeader(proxyReq);
        proxyConnection.flush();

        // it is possible to receive informational status
        // codes prior to receiving actual headers;
        // all those status codes are smaller than OK 200
        // a loop is a standard way of dealing with them
        do {
          statusLine = proxyConnection.parseResponseHeader(headers);
          statusCode = statusLine.getStatusCode();
        } while (statusCode < HttpStatus.SC_OK);
      } catch (ParseException e) {
        String errorMessage = e.getMessage();
        if (errorMessage == null) {
          errorMessage = "failed to send a CONNECT request";
        }

        throw new IOException(errorMessage);
      } catch (HttpException e) {
        String errorMessage = e.getMessage();
        if (errorMessage == null) {
          errorMessage = "failed to send a CONNECT request";
        }

        throw new IOException(errorMessage);
      } catch (IOException e) {
        String errorMessage = e.getMessage();
        if (errorMessage == null) {
          errorMessage = "failed to send a CONNECT request";
        }

        throw new IOException(errorMessage);
      }

      if (statusCode == HttpStatus.SC_OK) {
        try {
          sslSock =
              (SSLSocket)
                  getSocketFactory()
                      .createSocket(proxySock, mHost.getHostName(), mHost.getPort(), true);
        } catch (IOException e) {
          if (sslSock != null) {
            sslSock.close();
          }

          String errorMessage = e.getMessage();
          if (errorMessage == null) {
            errorMessage = "failed to create an SSL socket";
          }
          throw new IOException(errorMessage);
        }
      } else {
        // if the code is not OK, inform the event handler
        ProtocolVersion version = statusLine.getProtocolVersion();

        req.mEventHandler.status(
            version.getMajor(), version.getMinor(), statusCode, statusLine.getReasonPhrase());
        req.mEventHandler.headers(headers);
        req.mEventHandler.endData();

        proxyConnection.close();

        // here, we return null to indicate that the original
        // request needs to be dropped
        return null;
      }
    } else {
      // if we do not have a proxy, we simply connect to the host
      try {
        sslSock = (SSLSocket) getSocketFactory().createSocket(mHost.getHostName(), mHost.getPort());
        sslSock.setSoTimeout(SOCKET_TIMEOUT);
      } catch (IOException e) {
        if (sslSock != null) {
          sslSock.close();
        }

        String errorMessage = e.getMessage();
        if (errorMessage == null) {
          errorMessage = "failed to create an SSL socket";
        }

        throw new IOException(errorMessage);
      }
    }

    // do handshake and validate server certificates
    SslError error =
        CertificateChainValidator.getInstance()
            .doHandshakeAndValidateServerCertificates(this, sslSock, mHost.getHostName());

    // Inform the user if there is a problem
    if (error != null) {
      // handleSslErrorRequest may immediately unsuspend if it wants to
      // allow the certificate anyway.
      // So we mark the connection as suspended, call handleSslErrorRequest
      // then check if we're still suspended and only wait if we actually
      // need to.
      synchronized (mSuspendLock) {
        mSuspended = true;
      }
      // don't hold the lock while calling out to the event handler
      boolean canHandle = req.getEventHandler().handleSslErrorRequest(error);
      if (!canHandle) {
        throw new IOException("failed to handle " + error);
      }
      synchronized (mSuspendLock) {
        if (mSuspended) {
          try {
            // Put a limit on how long we are waiting; if the timeout
            // expires (which should never happen unless you choose
            // to ignore the SSL error dialog for a very long time),
            // we wake up the thread and abort the request. This is
            // to prevent us from stalling the network if things go
            // very bad.
            mSuspendLock.wait(10 * 60 * 1000);
            if (mSuspended) {
              // mSuspended is true if we have not had a chance to
              // restart the connection yet (ie, the wait timeout
              // has expired)
              mSuspended = false;
              mAborted = true;
              if (HttpLog.LOGV) {
                HttpLog.v(
                    "HttpsConnection.openConnection():"
                        + " SSL timeout expired and request was cancelled!!!");
              }
            }
          } catch (InterruptedException e) {
            // ignore
          }
        }
        if (mAborted) {
          // The user decided not to use this unverified connection
          // so close it immediately.
          sslSock.close();
          throw new SSLConnectionClosedByUserException("connection closed by the user");
        }
      }
    }

    // All went well, we have an open, verified connection.
    AndroidHttpClientConnection conn = new AndroidHttpClientConnection();
    BasicHttpParams params = new BasicHttpParams();
    params.setIntParameter(HttpConnectionParams.SOCKET_BUFFER_SIZE, 8192);
    conn.bind(sslSock, params);

    return conn;
  }
示例#4
0
 public static List<YouTubeVideo> searchForMatchingVideos(
     String paramString, int paramInt1, int paramInt2) {
   ArrayList localArrayList = new ArrayList();
   try {
     String str1 = URLEncoder.encode(paramString, "utf-8");
     String str2 = str1;
     Uri.Builder localBuilder1 =
         Uri.parse("https://gdata.youtube.com/feeds/api/videos")
             .buildUpon()
             .appendQueryParameter("q", paramString)
             .appendQueryParameter("alt", "json");
     String str3 = YOUTUBE_FORMAT_SHOCKWAVE_FLASH_STRING;
     Uri.Builder localBuilder2 =
         localBuilder1
             .appendQueryParameter("format", str3)
             .appendQueryParameter("v", "2")
             .appendQueryParameter(
                 "key",
                 "AI39si7E6CHtSMfmqL04cFEUgotVb0C6eozj6Nb9M4EsFxZ-hCKWVwpFfRemzEQ0o8pTlkW_U6d6lF23MY1etGLlY18QkfBDeA")
             .appendQueryParameter("orderby", "relevance");
     String str4 = String.valueOf(paramInt1);
     Uri.Builder localBuilder3 = localBuilder2.appendQueryParameter("start-index", str4);
     String str5 = String.valueOf(paramInt2);
     str6 =
         localBuilder3
             .appendQueryParameter("max-results", str5)
             .appendQueryParameter(
                 "fields",
                 "entry(author,yt:statistics,yt:hd,media:group(media:content,media:title,media:thumbnail))")
             .build()
             .toString();
   } catch (UnsupportedEncodingException localUnsupportedEncodingException) {
     try {
       String str6;
       BasicHttpParams localBasicHttpParams = new BasicHttpParams();
       Boolean localBoolean = Boolean.TRUE;
       HttpParams localHttpParams =
           localBasicHttpParams.setParameter("http.protocol.handle-redirects", localBoolean);
       HttpConnectionParams.setConnectionTimeout(localBasicHttpParams, 10000);
       HttpConnectionParams.setSoTimeout(localBasicHttpParams, 10000);
       DefaultHttpClient localDefaultHttpClient = new DefaultHttpClient(localBasicHttpParams);
       HttpGet localHttpGet = new HttpGet(str6);
       HttpResponse localHttpResponse = localDefaultHttpClient.execute(localHttpGet);
       StatusLine localStatusLine = localHttpResponse.getStatusLine();
       if ((localStatusLine != null) && (localStatusLine.getStatusCode() == 200)) {
         String str7 = EntityUtils.toString(localHttpResponse.getEntity());
         if (str7 != null) {
           JSONArray localJSONArray = getEntries(str7);
           if (localJSONArray != null) parseEntries(localJSONArray, localArrayList);
         }
       }
       while (true) {
         return localArrayList;
         localUnsupportedEncodingException = localUnsupportedEncodingException;
         Log.e("YouTubeUtils", "Unsupported encoding");
       }
     } catch (IOException localIOException) {
       while (true) {
         StringBuilder localStringBuilder1 =
             new StringBuilder().append("Error querying YouTube gdata API.  ");
         String str8 = localIOException.toString();
         String str9 = str8;
         Log.v("YouTubeUtils", str9);
       }
     } catch (JSONException localJSONException) {
       while (true) {
         StringBuilder localStringBuilder2 = new StringBuilder().append("Error in JSON.  ");
         String str10 = localJSONException.toString();
         String str11 = str10;
         Log.v("YouTubeUtils", str11);
       }
     }
   }
 }