Beispiel #1
0
 private static DefaultHttpClient createHttpClient() {
   DefaultHttpClient defaulthttpclient = new DefaultHttpClient();
   DefaultHttpClient defaulthttpclient1;
   try {
     SchemeRegistry schemeregistry = new SchemeRegistry();
     KeyStore keystore = KeyStore.getInstance(KeyStore.getDefaultType());
     keystore.load(null, null);
     CustomSSLSocketFactory customsslsocketfactory = new CustomSSLSocketFactory(keystore);
     customsslsocketfactory.setHostnameVerifier(SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);
     schemeregistry.register(new Scheme("http", PlainSocketFactory.getSocketFactory(), 80));
     schemeregistry.register(new Scheme("https", customsslsocketfactory, 443));
     BasicHttpParams basichttpparams = new BasicHttpParams();
     HttpProtocolParams.setVersion(basichttpparams, HttpVersion.HTTP_1_1);
     HttpProtocolParams.setContentCharset(basichttpparams, "UTF-8");
     HttpProtocolParams.setUseExpectContinue(basichttpparams, false);
     HttpConnectionParams.setConnectionTimeout(basichttpparams, HttpConst.NETWORK_TIME_OUT);
     HttpConnectionParams.setSoTimeout(basichttpparams, HttpConst.NETWORK_TIME_OUT);
     defaulthttpclient1 =
         new DefaultHttpClient(
             new ThreadSafeClientConnManager(basichttpparams, schemeregistry), basichttpparams);
     defaulthttpclient1.setHttpRequestRetryHandler(new DefaultHttpRequestRetryHandler(3, false));
     defaulthttpclient1
         .getCredentialsProvider()
         .setCredentials(
             new AuthScope(null, -1), new UsernamePasswordCredentials("admin", "admin"));
     defaulthttpclient = defaulthttpclient1;
   } catch (Exception e) {
     e.printStackTrace();
   }
   return defaulthttpclient;
 }
  /**
   * new {@link DefaultHttpClient}, and set strategy.
   *
   * @return DefaultHttpClient
   */
  private DefaultHttpClient createApacheHttpClient(BasicHttpParams httpParams) {
    DefaultHttpClient httpClient =
        new DefaultHttpClient(createClientConnManager(httpParams), httpParams);
    // disable apache default redirect handler
    httpClient.setRedirectHandler(
        new RedirectHandler() {

          @Override
          public boolean isRedirectRequested(HttpResponse response, HttpContext context) {
            return false;
          }

          @Override
          public URI getLocationURI(HttpResponse response, HttpContext context)
              throws ProtocolException {
            return null;
          }
        });
    // disable apache default retry handler
    httpClient.setHttpRequestRetryHandler(
        new HttpRequestRetryHandler() {
          @Override
          public boolean retryRequest(
              IOException exception, int executionCount, HttpContext context) {
            return false;
          }
        });
    // enable gzip supporting in request
    httpClient.addRequestInterceptor(
        new HttpRequestInterceptor() {
          @Override
          public void process(org.apache.http.HttpRequest request, HttpContext context) {
            if (!request.containsHeader(Consts.HEADER_ACCEPT_ENCODING)) {
              request.addHeader(Consts.HEADER_ACCEPT_ENCODING, Consts.ENCODING_GZIP);
            }
          }
        });
    // enable gzip supporting in response
    httpClient.addResponseInterceptor(
        new HttpResponseInterceptor() {
          @Override
          public void process(HttpResponse response, HttpContext context) {
            final HttpEntity entity = response.getEntity();
            if (entity == null) {
              return;
            }
            final Header encoding = entity.getContentEncoding();
            if (encoding != null) {
              for (HeaderElement element : encoding.getElements()) {
                if (element.getName().equalsIgnoreCase(Consts.ENCODING_GZIP)) {
                  response.setEntity(new GZIPEntityWrapper(entity));
                  break;
                }
              }
            }
          }
        });
    // setKeepAlive(httpClient);
    return httpClient;
  }
  private static HttpClient createHttpClient(
      String host, int port, String username, String password) {
    PoolingClientConnectionManager connectionPool = new PoolingClientConnectionManager();
    DefaultHttpClient httpClient = new DefaultHttpClient(connectionPool);
    SchemeRegistry schemeRegistry = httpClient.getConnectionManager().getSchemeRegistry();
    schemeRegistry.register(new Scheme("http", 80, PlainSocketFactory.getSocketFactory()));
    try {
      schemeRegistry.register(
          new Scheme(
              "https",
              443,
              new SSLSocketFactory(
                  new TrustStrategy() {
                    @Override
                    public boolean isTrusted(X509Certificate[] chain, String authType)
                        throws CertificateException {
                      return true;
                    }
                  },
                  new AllowAllHostnameVerifier())));
    } catch (Exception e) {
      throw new RuntimeException(e);
    }
    httpClient.setHttpRequestRetryHandler(new StandardHttpRequestRetryHandler(5, true));
    httpClient
        .getCredentialsProvider()
        .setCredentials(
            new AuthScope(host, port, MANAGEMENT_REALM, AuthPolicy.DIGEST),
            new UsernamePasswordCredentials(username, password));

    return httpClient;
  }
    public static synchronized DefaultHttpClient getThreadSafeClient() {

      if (clientThreadSafe != null) return clientThreadSafe;

      clientThreadSafe = new DefaultHttpClient();

      ClientConnectionManager mgr = clientThreadSafe.getConnectionManager();

      HttpParams params = clientThreadSafe.getParams();

      // timeout
      // int timeoutConnection = 25000;
      int timeoutConnection = 10000;
      HttpConnectionParams.setConnectionTimeout(params, timeoutConnection);
      // int timeoutSocket = 25000;
      int timeoutSocket = 10000;
      HttpConnectionParams.setSoTimeout(params, timeoutSocket);
      clientThreadSafe =
          new DefaultHttpClient(
              new ThreadSafeClientConnManager(params, mgr.getSchemeRegistry()), params);

      // disable requery
      clientThreadSafe.setHttpRequestRetryHandler(new DefaultHttpRequestRetryHandler(0, false));
      // persistent cookies
      clientThreadSafe.setCookieStore(SmartLibMU.getCookieStore());

      return clientThreadSafe;
    }
Beispiel #5
0
  public HttpUtils(int connTimeout, String userAgent) {
    HttpParams params = new BasicHttpParams();

    ConnManagerParams.setTimeout(params, connTimeout);
    HttpConnectionParams.setSoTimeout(params, connTimeout);
    HttpConnectionParams.setConnectionTimeout(params, connTimeout);

    if (TextUtils.isEmpty(userAgent)) {
      userAgent = OtherUtils.getUserAgent(null);
    }
    HttpProtocolParams.setUserAgent(params, userAgent);

    ConnManagerParams.setMaxConnectionsPerRoute(params, new ConnPerRouteBean(10));
    ConnManagerParams.setMaxTotalConnections(params, 10);

    HttpConnectionParams.setTcpNoDelay(params, true);
    HttpConnectionParams.setSocketBufferSize(params, 1024 * 8);
    HttpProtocolParams.setVersion(params, HttpVersion.HTTP_1_1);

    SchemeRegistry schemeRegistry = new SchemeRegistry();
    schemeRegistry.register(new Scheme("http", PlainSocketFactory.getSocketFactory(), 80));
    schemeRegistry.register(new Scheme("https", DefaultSSLSocketFactory.getSocketFactory(), 443));

    httpClient =
        new DefaultHttpClient(new ThreadSafeClientConnManager(params, schemeRegistry), params);

    httpClient.setHttpRequestRetryHandler(new RetryHandler(DEFAULT_RETRY_TIMES));

    httpClient.addRequestInterceptor(
        new HttpRequestInterceptor() {
          @Override
          public void process(org.apache.http.HttpRequest httpRequest, HttpContext httpContext)
              throws org.apache.http.HttpException, IOException {
            if (!httpRequest.containsHeader(HEADER_ACCEPT_ENCODING)) {
              httpRequest.addHeader(HEADER_ACCEPT_ENCODING, ENCODING_GZIP);
            }
          }
        });

    httpClient.addResponseInterceptor(
        new HttpResponseInterceptor() {
          @Override
          public void process(HttpResponse response, HttpContext httpContext)
              throws org.apache.http.HttpException, IOException {
            final HttpEntity entity = response.getEntity();
            if (entity == null) {
              return;
            }
            final Header encoding = entity.getContentEncoding();
            if (encoding != null) {
              for (HeaderElement element : encoding.getElements()) {
                if (element.getName().equalsIgnoreCase("gzip")) {
                  response.setEntity(new GZipDecompressingEntity(response.getEntity()));
                  return;
                }
              }
            }
          }
        });
  }
Beispiel #6
0
  /** Creates a new AsyncHttpClient. */
  public AsyncHttpClient() {
    BasicHttpParams httpParams = new BasicHttpParams();

    ConnManagerParams.setTimeout(httpParams, socketTimeout);
    ConnManagerParams.setMaxConnectionsPerRoute(httpParams, new ConnPerRouteBean(maxConnections));
    ConnManagerParams.setMaxTotalConnections(httpParams, DEFAULT_MAX_CONNECTIONS);

    HttpConnectionParams.setSoTimeout(httpParams, socketTimeout);
    HttpConnectionParams.setTcpNoDelay(httpParams, true);
    HttpConnectionParams.setSocketBufferSize(httpParams, DEFAULT_SOCKET_BUFFER_SIZE);

    HttpProtocolParams.setVersion(httpParams, HttpVersion.HTTP_1_1);
    HttpProtocolParams.setUserAgent(
        httpParams,
        String.format("android-async-http/%s (http://loopj.com/android-async-http)", VERSION));

    SchemeRegistry schemeRegistry = new SchemeRegistry();
    schemeRegistry.register(new Scheme("http", PlainSocketFactory.getSocketFactory(), 80));
    schemeRegistry.register(new Scheme("https", SSLSocketFactory.getSocketFactory(), 443));
    ThreadSafeClientConnManager cm = new ThreadSafeClientConnManager(httpParams, schemeRegistry);

    httpContext = new SyncBasicHttpContext(new BasicHttpContext());
    httpClient = new DefaultHttpClient(cm, httpParams);
    httpClient.addRequestInterceptor(
        new HttpRequestInterceptor() {
          public void process(HttpRequest request, HttpContext context) {
            if (!request.containsHeader(HEADER_ACCEPT_ENCODING)) {
              request.addHeader(HEADER_ACCEPT_ENCODING, ENCODING_GZIP);
            }
            for (String header : clientHeaderMap.keySet()) {
              request.addHeader(header, clientHeaderMap.get(header));
            }
          }
        });

    httpClient.addResponseInterceptor(
        new HttpResponseInterceptor() {
          public void process(HttpResponse response, HttpContext context) {
            final HttpEntity entity = response.getEntity();
            final Header encoding = entity.getContentEncoding();
            if (encoding != null) {
              for (HeaderElement element : encoding.getElements()) {
                if (element.getName().equalsIgnoreCase(ENCODING_GZIP)) {
                  response.setEntity(new InflatingEntity(response.getEntity()));
                  break;
                }
              }
            }
          }
        });

    httpClient.setHttpRequestRetryHandler(new RetryHandler(DEFAULT_MAX_RETRIES));

    threadPool = (ThreadPoolExecutor) Executors.newCachedThreadPool();

    requestMap = new WeakHashMap<Context, List<WeakReference<Future<?>>>>();
    clientHeaderMap = new HashMap<String, String>();
  }
 private void configureRetryHandler(DefaultHttpClient httpClient) {
   httpClient.setHttpRequestRetryHandler(
       new HttpRequestRetryHandler() {
         public boolean retryRequest(
             IOException exception, int executionCount, HttpContext context) {
           return false;
         }
       });
 }
Beispiel #8
0
  /**
   * 获得没有任何设置的实例
   *
   * @return
   */
  public static HttpClient getCleanHttpClient() {
    DefaultHttpClient httpClient = new DefaultHttpClient(getHttpParams());
    // httpClient.getParams().setParameter(ConnRoutePNames.DEFAULT_PROXY,
    // new HttpHost("localhost", 8888));

    httpClient.addRequestInterceptor(getRequestInter());
    httpClient.addResponseInterceptor(getResponseInter());
    httpClient.setHttpRequestRetryHandler(buildMyRetryHandler());

    return httpClient;
  }
  public static synchronized HttpClient getInstance(Context context) {
    if (null == customerHttpClient) {

      HttpParams params = new BasicHttpParams();

      // 设置一些基本参数
      HttpProtocolParams.setVersion(params, HttpVersion.HTTP_1_1);
      HttpProtocolParams.setContentCharset(params, CHARSET);
      HttpProtocolParams.setUseExpectContinue(params, true);
      HttpProtocolParams.setUserAgent(
          params, System.getProperties().getProperty("http.agent") + " Mozilla/5.0 Firefox/26.0");

      // 超时设置
      /* 从连接池中取连接的超时时间 */
      ConnManagerParams.setTimeout(params, 10 * 1000);

      /* 连接超时 */
      HttpConnectionParams.setConnectionTimeout(params, 10 * 1000);

      /* 请求超时 */
      HttpConnectionParams.setSoTimeout(params, 10 * 1000);

      // 支持http和https两种模式
      SchemeRegistry schReg = new SchemeRegistry();
      schReg.register(new Scheme("http", PlainSocketFactory.getSocketFactory(), 80));
      schReg.register(new Scheme("https", getSSLSocketFactory(), 443));

      // 使用线程安全的连接管理来创建HttpClient
      ClientConnectionManager conMgr = new ThreadSafeClientConnManager(params, schReg);

      customerHttpClient = new DefaultHttpClient(conMgr, params);
      customerHttpClient.setHttpRequestRetryHandler(requestRetryHandler);
      ConnectivityManager manager =
          (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);

      NetworkInfo networkinfo = manager.getActiveNetworkInfo();
      String net = networkinfo != null ? networkinfo.getExtraInfo() : null;

      // wifi的值为空
      if (!TextUtils.isEmpty(net)) {
        String proxyHost = getDefaultHost();

        if (!TextUtils.isEmpty(proxyHost)) {
          HttpHost proxy = new HttpHost(proxyHost, getDefaultPort(), "http");

          customerHttpClient.getParams().setParameter(ConnRoutePNames.DEFAULT_PROXY, proxy);
        }
      }
    }
    return customerHttpClient;
  }
Beispiel #10
0
  private static DefaultHttpClient getDefaultHttpClient(final String charset) {

    DefaultHttpClient httpclient = new DefaultHttpClient();

    httpclient.getParams().setParameter(CoreConnectionPNames.CONNECTION_TIMEOUT, 5000);
    httpclient.getParams().setParameter(CoreConnectionPNames.SO_TIMEOUT, 5000);
    httpclient
        .getParams()
        .setParameter(
            CoreProtocolPNames.HTTP_CONTENT_CHARSET, charset == null ? CHARSET_UTF8 : charset);
    httpclient.setHttpRequestRetryHandler(requestRetryHandler);

    return httpclient;
  }
 /* (non-Javadoc)
  * @see java.net.URLConnection#connect()
  */
 @Override
 public void connect() throws IOException {
   if (m_client != null) {
     return;
   }
   final HttpParams httpParams = new BasicHttpParams();
   if (m_request != null) {
     int timeout = m_request.getParameterAsInt("timeout");
     if (timeout > 0) {
       HttpConnectionParams.setConnectionTimeout(httpParams, timeout);
       HttpConnectionParams.setSoTimeout(httpParams, timeout);
     }
   }
   m_client = new DefaultHttpClient(httpParams);
   m_client.addRequestInterceptor(new RequestAcceptEncoding());
   m_client.addResponseInterceptor(new ResponseContentEncoding());
   if (m_request != null) {
     int retries = m_request.getParameterAsInt("retries");
     if (retries > 0) {
       m_client.setHttpRequestRetryHandler(
           new DefaultHttpRequestRetryHandler() {
             @Override
             public boolean retryRequest(
                 IOException exception, int executionCount, HttpContext context) {
               if (executionCount <= getRetryCount()
                   && (exception instanceof SocketTimeoutException
                       || exception instanceof ConnectTimeoutException)) {
                 return true;
               }
               return super.retryRequest(exception, executionCount, context);
             }
           });
     }
     String disableSslVerification = m_request.getParameter("disable-ssl-verification");
     if (Boolean.parseBoolean(disableSslVerification)) {
       final SchemeRegistry registry = m_client.getConnectionManager().getSchemeRegistry();
       final Scheme https = registry.getScheme("https");
       try {
         SSLSocketFactory factory =
             new SSLSocketFactory(
                 SSLContext.getInstance(EmptyKeyRelaxedTrustSSLContext.ALGORITHM),
                 SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);
         final Scheme lenient = new Scheme(https.getName(), https.getDefaultPort(), factory);
         registry.register(lenient);
       } catch (NoSuchAlgorithmException e) {
         LOG.warn(e.getMessage());
       }
     }
   }
 }
Beispiel #12
0
  /**
   * 获得连接池的实例
   *
   * @return
   */
  public static HttpClient getCoonPoolHttpClient() {

    PoolingClientConnectionManager cm = new PoolingClientConnectionManager();
    cm.setMaxTotal(800);
    cm.setDefaultMaxPerRoute(200);

    DefaultHttpClient httpClient = new DefaultHttpClient(cm, getHttpParams());

    httpClient.addRequestInterceptor(getRequestInter());
    httpClient.addResponseInterceptor(getResponseInter());
    httpClient.setHttpRequestRetryHandler(buildMyRetryHandler());

    return httpClient;
  }
  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;
  }
  public void setPbapiHttpClient(final HttpClient httpClient) {
    HttpParams params = httpClient.getParams();
    // if there is proxy then set it.
    if (proxyHost != null) {
      HttpHost proxy = new HttpHost(proxyHost, proxyPort, "http");
      params.setParameter(ConnRoutePNames.DEFAULT_PROXY, proxy);
    }
    SchemeRegistry schemeRegistry = new SchemeRegistry();

    schemeRegistry.register(new Scheme("http", HTTP, PlainSocketFactory.getSocketFactory()));
    schemeRegistry.register(new Scheme("https", HTTPS, SSLSocketFactory.getSocketFactory()));
    ClientConnectionManager connectionManager = new ThreadSafeClientConnManager(schemeRegistry);

    DefaultHttpClient httpClientWithRetryHandler = new DefaultHttpClient(connectionManager, params);
    httpClientWithRetryHandler.setHttpRequestRetryHandler(
        new HttpRequestRetryHandler() {

          public boolean retryRequest(
              IOException exception, int executionCount, HttpContext context) {
            if (executionCount >= MAX_EXECUTION_COUNT) {
              return false;
            }
            if (exception instanceof NoHttpResponseException
                || exception instanceof SocketTimeoutException) {
              if (executionCount < MIN_EXECUTION_COUNT) {
                LOG.warn(
                    "pbapiHttpClient encountered exception '"
                        + exception.getMessage()
                        + "' retrying request, retryCount="
                        + executionCount);
              } else {
                LOG.error(
                    "pbapiHttpClient encountered exception '"
                        + exception.getMessage()
                        + "' retrying request, retryCount="
                        + executionCount);
              }
              return true;
            }

            return false;
          }
        });

    this.placesAPIHttpClient = httpClientWithRetryHandler;
  }
Beispiel #15
0
 private <S extends GenericResponse> S post(Object payload, boolean agressiveRetry)
     throws Exception {
   EndPointResponsePair endPointResponse =
       Preconditions.checkNotNull(
           REQUEST_TO_ENDPOINT.get(payload.getClass()), payload.getClass().getName());
   HttpPost request = new HttpPost(mApiEndPoint + endPointResponse.getEndpoint());
   try {
     String payloadString = mMapper.writeValueAsString(payload);
     StringEntity params = new StringEntity(payloadString);
     request.addHeader("content-type", "application/json");
     request.setEntity(params);
     if (agressiveRetry) {
       mHttpClient.setHttpRequestRetryHandler(new PTestHttpRequestRetryHandler());
     }
     HttpResponse httpResponse = mHttpClient.execute(request);
     StatusLine statusLine = httpResponse.getStatusLine();
     if (statusLine.getStatusCode() != 200) {
       throw new IllegalStateException(
           statusLine.getStatusCode() + " " + statusLine.getReasonPhrase());
     }
     String response = EntityUtils.toString(httpResponse.getEntity(), "UTF-8");
     @SuppressWarnings("unchecked")
     S result =
         (S)
             endPointResponse
                 .getResponseClass()
                 .cast(mMapper.readValue(response, endPointResponse.getResponseClass()));
     Status.assertOK(result.getStatus());
     if (System.getProperty("DEBUG_PTEST_CLIENT") != null) {
       System.err.println("payload " + payloadString);
       if (result instanceof TestLogResponse) {
         System.err.println(
             "response "
                 + ((TestLogResponse) result).getOffset()
                 + " "
                 + ((TestLogResponse) result).getStatus());
       } else {
         System.err.println("response " + response);
       }
     }
     Thread.sleep(1000);
     return result;
   } finally {
     request.abort();
   }
 }
  /**
   * Prepares objects for HTTP communications with the Gatekeeper servlet.
   *
   * @return
   */
  private HttpClient initHttpConnection() {
    // Set client parameters.
    HttpParams params = RestUtils.createDefaultHttpParams();
    HttpProtocolParams.setUserAgent(
        params, ServiceUtils.getUserAgentDescription(userAgentDescription));

    // Set connection parameters.
    HttpConnectionParams.setConnectionTimeout(params, connectionTimeout);
    HttpConnectionParams.setSoTimeout(params, connectionTimeout);
    HttpConnectionParams.setStaleCheckingEnabled(params, false);

    DefaultHttpClient httpClient = new DefaultHttpClient(params);
    // Replace default error retry handler.
    httpClient.setHttpRequestRetryHandler(new RestUtils.JetS3tRetryHandler(maxRetryCount, null));

    // httpClient.getParams().setAuthenticationPreemptive(true);
    httpClient.setCredentialsProvider(credentialsProvider);

    return httpClient;
  }
 public Bitmap getBitmapFromNet(String url, int width, int height) {
   Bitmap bitmap = null;
   DefaultHttpClient client = new DefaultHttpClient();
   client.getParams().setIntParameter(CoreConnectionPNames.SO_TIMEOUT, 60000);
   client.setHttpRequestRetryHandler(new DefaultHttpRequestRetryHandler(5, false));
   HttpGet get = new HttpGet();
   int retryCount = 0;
   try {
     get.setURI(new URI(url));
     HttpResponse response = client.execute(get);
     if (response.getStatusLine().getStatusCode() == 200) {
       bitmap = BitmapFactory.decodeStream(response.getEntity().getContent());
     }
     if (bitmap == null) {
       Log.e(TAG, "getBitmapFromNet 下载失败 " + retryCount + " 次, url = " + url);
     }
   } catch (Exception e) {
   } finally {
     get.abort();
     client.getConnectionManager().shutdown();
   }
   return bitmap;
 }
Beispiel #18
0
  private CacheManager(final Context context) {

    if (!isAlreadyInitialized.compareAndSet(false, true)) {
      throw new RuntimeException("Attempt to initialize the cache twice.");
    }

    this.context = context;

    dbManager = new CacheDbManager(context);

    RequestHandlerThread requestHandler = new RequestHandlerThread();

    // TODo put somewhere else -- make request specific, no restart needed on prefs change!
    final HttpParams params = new BasicHttpParams();
    params.setParameter(CoreProtocolPNames.USER_AGENT, Constants.ua(context));
    params.setParameter(
        CoreConnectionPNames.SO_TIMEOUT,
        20000); // TODO remove hardcoded params, put in network prefs
    params.setParameter(CoreConnectionPNames.CONNECTION_TIMEOUT, 20000);
    params.setParameter(CoreConnectionPNames.MAX_HEADER_COUNT, 100);
    params.setParameter(ClientPNames.HANDLE_REDIRECTS, true);
    params.setParameter(ClientPNames.MAX_REDIRECTS, 2);
    params.setParameter(ConnManagerPNames.MAX_TOTAL_CONNECTIONS, 50);
    params.setParameter(
        ConnManagerPNames.MAX_CONNECTIONS_PER_ROUTE,
        new ConnPerRoute() {
          public int getMaxForRoute(HttpRoute route) {
            return 25;
          }
        });

    final SchemeRegistry schemeRegistry = new SchemeRegistry();
    schemeRegistry.register(new Scheme("http", PlainSocketFactory.getSocketFactory(), 80));
    schemeRegistry.register(new Scheme("https", SSLSocketFactory.getSocketFactory(), 443));

    final ThreadSafeClientConnManager connManager =
        new ThreadSafeClientConnManager(params, schemeRegistry);

    final DefaultHttpClient defaultHttpClient = new DefaultHttpClient(connManager, params);
    defaultHttpClient.setHttpRequestRetryHandler(new DefaultHttpRequestRetryHandler(3, true));

    defaultHttpClient.addResponseInterceptor(
        new HttpResponseInterceptor() {

          public void process(final HttpResponse response, final HttpContext context)
              throws HttpException, IOException {

            final HttpEntity entity = response.getEntity();
            final Header encHeader = entity.getContentEncoding();

            if (encHeader == null) return;

            for (final HeaderElement elem : encHeader.getElements()) {
              if ("gzip".equalsIgnoreCase(elem.getName())) {
                response.setEntity(new GzipDecompressingEntity(entity));
                return;
              }
            }
          }
        });

    downloadQueue = new PrioritisedDownloadQueue(defaultHttpClient);

    requestHandler.start();

    for (int i = 0; i < 5; i++) { // TODO remove constant --- customizable
      final CacheDownloadThread downloadThread = new CacheDownloadThread(downloadQueue, true);
      downloadThreads.add(downloadThread);
    }
  }
Beispiel #19
0
  private static void httpInit() {
    try {
      HttpParams params = new BasicHttpParams();
      params.setParameter(CoreConnectionPNames.CONNECTION_TIMEOUT, Integer.valueOf(30000));
      params.setParameter(CoreConnectionPNames.SO_TIMEOUT, Integer.valueOf(50000)); // 设置20秒socket超时
      params.setLongParameter(ConnManagerPNames.TIMEOUT, 30000);
      params.setBooleanParameter(CoreProtocolPNames.USE_EXPECT_CONTINUE, false);
      params.setParameter(
          CoreConnectionPNames.SOCKET_BUFFER_SIZE,
          Integer.valueOf(8192 * 3)); // 默认是8192 byte socket buffers
      ConnManagerParams.setMaxTotalConnections(params, 200);
      ConnPerRouteBean connPerRoute = new ConnPerRouteBean(20);
      HttpHost localhost = new HttpHost(INFO.HOST_IP, INFO.HOST_PORT);
      connPerRoute.setMaxForRoute(new HttpRoute(localhost), 50);
      ConnManagerParams.setMaxConnectionsPerRoute(params, connPerRoute);

      ////////////////////
      KeyStore trustStore = KeyStore.getInstance(KeyStore.getDefaultType());
      trustStore.load(null, null);
      SSLSocketFactory sf = new SSLSocketFactoryEx(trustStore);
      sf.setHostnameVerifier(SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);

      HttpProtocolParams.setVersion(params, HttpVersion.HTTP_1_1);
      HttpProtocolParams.setContentCharset(params, HTTP.UTF_8);
      ////////////////////////////////////

      SchemeRegistry schemeRegistry = new SchemeRegistry();
      schemeRegistry.register(new Scheme("http", PlainSocketFactory.getSocketFactory(), 80));
      schemeRegistry.register(new Scheme("https", sf, 443));
      ClientConnectionManager clientManager =
          new ThreadSafeClientConnManager(params, schemeRegistry);

      defaultHttpClient = new DefaultHttpClient(clientManager, params);
      defaultHttpClient.setKeepAliveStrategy(
          new DefaultConnectionKeepAliveStrategy() {
            public long getKeepAliveDuration(HttpResponse response, HttpContext context) {
              long keepAlive = super.getKeepAliveDuration(response, context);
              if (keepAlive == -1) {
                keepAlive = 5000;
              }

              return keepAlive;
            }
          });
      defaultHttpClient.addRequestInterceptor(preemptiveAuth, 0);
      defaultHttpClient.setHttpRequestRetryHandler(
          new HttpRequestRetryHandler() {
            public boolean retryRequest(
                IOException exception, int executionCount, HttpContext context) {
              // INFO.Log("NETWORKTEST>><<",exception.toString()+"##"+executionCount);
              if (executionCount >= 2) {
                return false;
              }
              if (exception instanceof NoHttpResponseException) {
                // 服务停掉则重新尝试连接
                // INFO.Log("NETWORKTEST>><<","port:"+INFO.HOST_PORT);
                return true;
              }
              if (exception instanceof UnknownHostException) {
                INFO.HOST_PORT = 8080;
                // INFO.Log("NETWORKTEST>><<","port:"+INFO.HOST_PORT);
                return true;
              }
              if (exception instanceof UnknownServiceException) {
                INFO.HOST_PORT = 8080;
                // INFO.Log("NETWORKTEST>><<","Service:"+INFO.HOST_PORT);
                return true;
              }
              if (exception instanceof SocketException) {
                // INFO.Log("NETWORKTEST>><<","SocketException");
                return true;
              }
              if (exception instanceof SSLHandshakeException) {
                return false;
              }
              HttpRequest request =
                  (HttpRequest) context.getAttribute(ExecutionContext.HTTP_REQUEST);
              boolean idempotent = !(request instanceof HttpEntityEnclosingRequest);
              if (idempotent) {
                return true;
              }
              return false;
            }
          });

    } catch (Exception ex) {
      ex.printStackTrace();
    }

    // ssl

    // FileInputStream instream = new FileInputStream(new File("my.keystore"));
    //		InputStream instream = appContext.getResources().openRawResource(R.drawable.adcd);  //读证书
    //		try {
    //			KeyStore trustStore  = KeyStore.getInstance(KeyStore.getDefaultType());
    // //KeyStore.getDefaultType()  android为 BKS
    //		    trustStore.load(instream, "nopassword".toCharArray());
    //		    SSLSocketFactory socketFactory = new SSLSocketFactory(trustStore);
    //			Scheme sch = new Scheme("https", socketFactory, 443);                     //443端口
    //			defaultHttpClient.getConnectionManager().getSchemeRegistry().register(sch);
    //		}catch(Exception e){
    //			e.printStackTrace();
    //		}finally {
    //		    try {
    //				instream.close();
    //			} catch (IOException e) {
    //				e.printStackTrace();
    //			}
    //		}

  }
  public Host(
      String server,
      String rootPath,
      Integer port,
      String user,
      String password,
      ProxyDetails proxyDetails,
      int timeoutMillis,
      Cache<Folder, List<Resource>> cache,
      FileSyncer fileSyncer) {
    super(
        (cache != null
            ? cache
            : new MemoryCache<Folder, List<Resource>>("resource-cache-default", 50, 20)));
    if (server == null) {
      throw new IllegalArgumentException("host name cannot be null");
    }
    this.rootPath = rootPath;
    this.timeout = timeoutMillis;
    this.server = server;
    this.port = port;
    this.user = user;
    this.password = password;
    client = new DefaultHttpClient();
    HttpParams params = client.getParams();
    HttpConnectionParams.setConnectionTimeout(params, 10000);
    HttpConnectionParams.setSoTimeout(params, 10000);

    if (user != null) {
      client
          .getCredentialsProvider()
          .setCredentials(AuthScope.ANY, new UsernamePasswordCredentials(user, password));
      PreemptiveAuthInterceptor interceptor = new PreemptiveAuthInterceptor();
      client.addRequestInterceptor(interceptor);
    }

    HttpRequestRetryHandler handler = new DefaultHttpRequestRetryHandler(0, false);
    client.setHttpRequestRetryHandler(handler);

    if (proxyDetails != null) {
      if (proxyDetails.isUseSystemProxy()) {
        System.setProperty("java.net.useSystemProxies", "true");
      } else {
        System.setProperty("java.net.useSystemProxies", "false");
        if (proxyDetails.getProxyHost() != null && proxyDetails.getProxyHost().length() > 0) {
          HttpHost proxy =
              new HttpHost(proxyDetails.getProxyHost(), proxyDetails.getProxyPort(), "http");
          client.getParams().setParameter(ConnRoutePNames.DEFAULT_PROXY, proxy);
          if (proxyDetails.hasAuth()) {
            client
                .getCredentialsProvider()
                .setCredentials(
                    new AuthScope(proxyDetails.getProxyHost(), proxyDetails.getProxyPort()),
                    new UsernamePasswordCredentials(
                        proxyDetails.getUserName(), proxyDetails.getPassword()));
          }
        }
      }
    }
    transferService = new TransferService(client, connectionListeners);
    transferService.setTimeout(timeoutMillis);
    this.fileSyncer = fileSyncer;
  }
  /**
   * Creates a new fetcher for fetching HTTP objects. Not really suitable for production use. Use of
   * an HTTP proxy for security is also necessary for production deployment.
   *
   * @param maxObjSize Maximum size, in bytes, of the object we will fetch, 0 if no limit..
   * @param connectionTimeoutMs timeout, in milliseconds, for connecting to hosts.
   * @param readTimeoutMs timeout, in millseconds, for unresponsive connections
   * @param basicHttpFetcherProxy The http proxy to use.
   */
  public BasicHttpFetcher(
      int maxObjSize, int connectionTimeoutMs, int readTimeoutMs, String basicHttpFetcherProxy) {
    // Create and initialize HTTP parameters
    setMaxObjectSizeBytes(maxObjSize);
    setSlowResponseWarning(DEFAULT_SLOW_RESPONSE_WARNING);

    HttpParams params = new BasicHttpParams();

    ConnManagerParams.setTimeout(params, connectionTimeoutMs);

    // These are probably overkill for most sites.
    ConnManagerParams.setMaxTotalConnections(params, 1152);
    ConnManagerParams.setMaxConnectionsPerRoute(params, new ConnPerRouteBean(256));

    HttpProtocolParams.setVersion(params, HttpVersion.HTTP_1_1);
    HttpProtocolParams.setUserAgent(params, "Apache Shindig");
    HttpProtocolParams.setContentCharset(params, "UTF-8");

    HttpConnectionParams.setConnectionTimeout(params, connectionTimeoutMs);
    HttpConnectionParams.setSoTimeout(params, readTimeoutMs);
    HttpConnectionParams.setStaleCheckingEnabled(params, true);

    HttpClientParams.setRedirecting(params, true);
    HttpClientParams.setAuthenticating(params, false);

    // Create and initialize scheme registry
    SchemeRegistry schemeRegistry = new SchemeRegistry();
    schemeRegistry.register(new Scheme("http", PlainSocketFactory.getSocketFactory(), 80));
    // UCSF. Change to allow self signed registered certs
    /**
     * try { SSLContext sslContext = SSLContext.getInstance("SSL"); // set up a TrustManager that
     * trusts everything sslContext.init(null, new TrustManager[] { new X509TrustManager() { public
     * X509Certificate[] getAcceptedIssuers() { System.out.println("getAcceptedIssuers
     * ============="); return null; }
     *
     * <p>public void checkClientTrusted(X509Certificate[] certs, String authType) {
     * System.out.println("checkClientTrusted ============="); }
     *
     * <p>public void checkServerTrusted(X509Certificate[] certs, String authType) {
     * System.out.println("checkServerTrusted ============="); } } }, new SecureRandom());
     * SSLSocketFactory sf = new SSLSocketFactory(sslContext);
     * sf.setHostnameVerifier((X509HostnameVerifier)org.apache.http.conn.ssl.SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);
     * schemeRegistry.register(new Scheme("https", sf, 443)); } catch (Exception e) { throw new
     * RuntimeException(e); }
     */
    schemeRegistry.register(new Scheme("https", SSLSocketFactory.getSocketFactory(), 443));
    // end UCSF

    ClientConnectionManager cm = new ThreadSafeClientConnManager(params, schemeRegistry);
    DefaultHttpClient client = new DefaultHttpClient(cm, params);

    // Set proxy if set via guice.
    if (!StringUtils.isEmpty(basicHttpFetcherProxy)) {
      String[] splits = basicHttpFetcherProxy.split(":");
      ConnRouteParams.setDefaultProxy(
          client.getParams(), new HttpHost(splits[0], Integer.parseInt(splits[1]), "http"));
    }

    // try resending the request once
    client.setHttpRequestRetryHandler(new DefaultHttpRequestRetryHandler(1, true));

    // Add hooks for gzip/deflate
    client.addRequestInterceptor(
        new HttpRequestInterceptor() {
          public void process(final org.apache.http.HttpRequest request, final HttpContext context)
              throws HttpException, IOException {
            if (!request.containsHeader("Accept-Encoding")) {
              request.addHeader("Accept-Encoding", "gzip, deflate");
            }
          }
        });
    client.addResponseInterceptor(
        new HttpResponseInterceptor() {
          public void process(
              final org.apache.http.HttpResponse response, final HttpContext context)
              throws HttpException, IOException {
            HttpEntity entity = response.getEntity();
            if (entity != null) {
              Header ceheader = entity.getContentEncoding();
              if (ceheader != null) {
                for (HeaderElement codec : ceheader.getElements()) {
                  String codecname = codec.getName();
                  if ("gzip".equalsIgnoreCase(codecname)) {
                    response.setEntity(new GzipDecompressingEntity(response.getEntity()));
                    return;
                  } else if ("deflate".equals(codecname)) {
                    response.setEntity(new DeflateDecompressingEntity(response.getEntity()));
                    return;
                  }
                }
              }
            }
          }
        });
    client.setHttpRequestRetryHandler(new DefaultHttpRequestRetryHandler());

    // Disable automatic storage and sending of cookies (see SHINDIG-1382)
    client.removeRequestInterceptorByClass(RequestAddCookies.class);
    client.removeResponseInterceptorByClass(ResponseProcessCookies.class);

    // Use Java's built-in proxy logic in case no proxy set via guice.
    if (StringUtils.isEmpty(basicHttpFetcherProxy)) {
      ProxySelectorRoutePlanner routePlanner =
          new ProxySelectorRoutePlanner(
              client.getConnectionManager().getSchemeRegistry(), ProxySelector.getDefault());
      client.setRoutePlanner(routePlanner);
    }

    FETCHER = client;
  }
  /**
   * Creates a new AsyncHttpClient and set timeout.
   *
   * @param timeout 超时时间
   */
  public AsyncHttpClient(int timeout) {
    this.socketTimeout = timeout;
    BasicHttpParams httpParams = new BasicHttpParams();

    ConnManagerParams.setTimeout(httpParams, socketTimeout);
    ConnManagerParams.setMaxConnectionsPerRoute(httpParams, new ConnPerRouteBean(maxConnections));
    ConnManagerParams.setMaxTotalConnections(httpParams, DEFAULT_MAX_CONNECTIONS);

    HttpConnectionParams.setSoTimeout(httpParams, socketTimeout);
    HttpConnectionParams.setTcpNoDelay(httpParams, true);
    HttpConnectionParams.setSocketBufferSize(httpParams, DEFAULT_SOCKET_BUFFER_SIZE);

    HttpProtocolParams.setVersion(httpParams, HttpVersion.HTTP_1_1);
    HttpProtocolParams.setUserAgent(
        httpParams,
        String.format("android-async-http/%s (http://loopj.com/android-async-http)", VERSION));

    SchemeRegistry schemeRegistry = new SchemeRegistry();
    SSLSocketFactory sf = null;
    try {
      KeyStore trustStore = KeyStore.getInstance(KeyStore.getDefaultType());
      trustStore.load(null, null);
      sf = new MySSLSocketFactory(trustStore);
    } catch (Exception e) {
      e.printStackTrace();
    }
    sf.setHostnameVerifier(SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);
    schemeRegistry.register(new Scheme("http", PlainSocketFactory.getSocketFactory(), 80));
    schemeRegistry.register(new Scheme("https", sf, 443));
    ThreadSafeClientConnManager cm = new ThreadSafeClientConnManager(httpParams, schemeRegistry);

    httpContext = new SyncBasicHttpContext(new BasicHttpContext());
    httpClient = new DefaultHttpClient(cm, httpParams);
    httpClient.addRequestInterceptor(
        new HttpRequestInterceptor() {
          public void process(HttpRequest request, HttpContext context) {
            if (!request.containsHeader(HEADER_ACCEPT_ENCODING)) {
              request.addHeader(HEADER_ACCEPT_ENCODING, ENCODING_GZIP);
            }
            for (String header : clientHeaderMap.keySet()) {
              request.addHeader(header, clientHeaderMap.get(header));
            }
          }
        });

    httpClient.addResponseInterceptor(
        new HttpResponseInterceptor() {
          public void process(HttpResponse response, HttpContext context) {
            final HttpEntity entity = response.getEntity();
            final Header encoding = entity.getContentEncoding();
            if (encoding != null) {
              for (HeaderElement element : encoding.getElements()) {
                if (element.getName().equalsIgnoreCase(ENCODING_GZIP)) {
                  response.setEntity(new InflatingEntity(response.getEntity()));
                  break;
                }
              }
            }
          }
        });

    httpClient.setHttpRequestRetryHandler(new RetryHandler(DEFAULT_MAX_RETRIES));
    /*   HttpHost proxy = NetworkUtils.getHttpHostProxy();
            if (proxy!=null) { // set proxy
            	  httpClient.getParams().setParameter(ConnRoutePNames.DEFAULT_PROXY, proxy);
    		}
    */ threadPool = (ThreadPoolExecutor) Executors.newCachedThreadPool();

    requestMap = new WeakHashMap<Context, List<WeakReference<Future<?>>>>();
    clientHeaderMap = new HashMap<String, String>();
  }