private HttpClient getHttpClient() {
   if (null == customerHttpClient) {
     HttpParams params = new BasicHttpParams();
     // 设置一些基本参数
     HttpProtocolParams.setVersion(params, HttpVersion.HTTP_1_1);
     HttpProtocolParams.setContentCharset(params, HTTP.UTF_8);
     HttpProtocolParams.setUseExpectContinue(params, true);
     HttpProtocolParams.setUserAgent(params, "Linux; Android 2.2.1;zh-CN; itkt_Android");
     //			HttpClientParams.setRedirecting(params, true);
     //		    HttpClientParams.setCookiePolicy(params, CookiePolicy.BROWSER_COMPATIBILITY);
     // 设置最大连接数
     ConnManagerParams.setMaxTotalConnections(params, MAX_TOTAL_CONNECTIONS);
     // 设置获取连接的最大等待时间
     ConnManagerParams.setTimeout(params, WAIT_TIMEOUT);
     // 设置每个路由最大连接数
     ConnPerRouteBean connPerRoute = new ConnPerRouteBean(MAX_ROUTE_CONNECTIONS);
     ConnManagerParams.setMaxConnectionsPerRoute(params, connPerRoute);
     // 设置连接超时时间
     HttpConnectionParams.setConnectionTimeout(params, CONNECT_TIMEOUT);
     // 设置读取超时时间
     HttpConnectionParams.setSoTimeout(params, READ_TIMEOUT);
     try {
       KeyStore trustStore = KeyStore.getInstance(KeyStore.getDefaultType());
       SchemeRegistry schReg = new SchemeRegistry();
       schReg.register(new Scheme("http", PlainSocketFactory.getSocketFactory(), 80));
       // 使用线程安全的连接管理来创建HttpClient
       ClientConnectionManager conMgr = new ThreadSafeClientConnManager(params, schReg);
       customerHttpClient = new DefaultHttpClient(conMgr, params);
       customerHttpClient.getParams().setParameter("http.protocol.content-charset", HTTP.UTF_8);
     } catch (Exception e) {
       e.printStackTrace();
     }
   }
   return customerHttpClient;
 }
Exemplo n.º 2
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;
                }
              }
            }
          }
        });
  }
Exemplo n.º 3
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>();
  }
Exemplo n.º 4
0
  public Http(Context context) {
    BasicHttpParams httpParams = new BasicHttpParams();

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

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

    HttpProtocolParams.setVersion(httpParams, HttpVersion.HTTP_1_1);

    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();
            if (entity == null) {
              return;
            }
            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;
                }
              }
            }
          }
        });

    clientHeaderMap = new HashMap<String, String>();
  }
Exemplo n.º 5
0
 private static void setupHttpClient() {
   BasicHttpParams httpParams = new BasicHttpParams();
   ConnManagerParams.setTimeout(httpParams, CONNECTION_TIMEOUT);
   ConnManagerParams.setMaxConnectionsPerRoute(httpParams, new ConnPerRouteBean(MAX_CONNECTIONS));
   ConnManagerParams.setMaxTotalConnections(httpParams, MAX_CONNECTIONS);
   HttpProtocolParams.setVersion(httpParams, HttpVersion.HTTP_1_1);
   HttpProtocolParams.setUserAgent(httpParams, HTTP_USER_AGENT);
   SchemeRegistry schemeRegistry = new SchemeRegistry();
   schemeRegistry.register(new Scheme("http", PlainSocketFactory.getSocketFactory(), 80));
   // schemeRegistry.register(new Scheme("https", new
   // EasySSLProtocolSocketFactory(), 443));
   ThreadSafeClientConnManager cm = new ThreadSafeClientConnManager(httpParams, schemeRegistry);
   HttpProtocolParams.setContentCharset(httpParams, HTTP.UTF_8);
   httpClient = new DefaultHttpClient(cm, httpParams);
 }
 /** initialize HttpParams , initialize settings such as total connextions,timeout ... */
 private BasicHttpParams createHttpParams() {
   BasicHttpParams params = new BasicHttpParams();
   ConnManagerParams.setTimeout(params, config.getConnectTimeout());
   ConnManagerParams.setMaxConnectionsPerRoute(
       params, new ConnPerRouteBean(DEFAULT_MAX_CONN_PER_ROUT));
   ConnManagerParams.setMaxTotalConnections(params, DEFAULT_MAX_CONN_TOTAL);
   HttpConnectionParams.setTcpNoDelay(params, TCP_NO_DELAY);
   HttpConnectionParams.setConnectionTimeout(params, config.getConnectTimeout());
   HttpConnectionParams.setSoTimeout(params, config.getSocketTimeout());
   HttpConnectionParams.setSocketBufferSize(params, config.getSocketBufferSize());
   HttpProtocolParams.setVersion(params, HttpVersion.HTTP_1_1);
   HttpProtocolParams.setUserAgent(params, config.getUserAgent());
   // settingOthers(params);
   return params;
 }
  private static DefaultHttpClient clientFactory() {

    SchemeRegistry sr = new SchemeRegistry();
    sr.register(new Scheme("http", PlainSocketFactory.getSocketFactory(), 80));

    BasicHttpParams params = new BasicHttpParams();
    HttpConnectionParams.setConnectionTimeout(params, CONN_TIMEOUT);
    HttpConnectionParams.setSoTimeout(params, CONN_TIMEOUT);
    ConnManagerParams.setMaxTotalConnections(params, MAX_TOTAL_CONN);
    ConnManagerParams.setMaxConnectionsPerRoute(params, new ConnPerRouteBean(MAX_CONN_PER_ROUTE));

    ThreadSafeClientConnManager mgr = new ThreadSafeClientConnManager(params, sr);
    DefaultHttpClient client = new DefaultHttpClient(mgr, params);
    return client;
  }
Exemplo n.º 8
0
  private String doGet(String url) {
    String responseStr = "";
    try {
      HttpGet httpRequest = new HttpGet(url);
      HttpParams params = new BasicHttpParams();
      ConnManagerParams.setTimeout(params, 1000);
      HttpConnectionParams.setConnectionTimeout(params, 3000);
      HttpConnectionParams.setSoTimeout(params, 5000);
      httpRequest.setParams(params);

      HttpResponse httpResponse = new DefaultHttpClient().execute(httpRequest);
      final int ret = httpResponse.getStatusLine().getStatusCode();
      if (ret == HttpStatus.SC_OK) {
        responseStr = EntityUtils.toString(httpResponse.getEntity(), HTTP.UTF_8);
      } else {
        responseStr = "-1";
      }
    } catch (ClientProtocolException e) {
      // TODO Auto-generated catch block
      e.printStackTrace();
    } catch (IOException e) {
      // TODO Auto-generated catch block
      e.printStackTrace();
    }

    return responseStr;
  }
Exemplo n.º 9
0
  protected DefaultHttpClient getHttpClient() {
    if (httpClient == null) {
      HttpParams httpParams = new BasicHttpParams();
      HttpProtocolParams.setVersion(httpParams, HttpVersion.HTTP_1_1);
      HttpProtocolParams.setContentCharset(httpParams, HTTP.UTF_8);
      HttpProtocolParams.setUseExpectContinue(
          httpParams, false); // some webservers have problems if this is set to true
      ConnManagerParams.setMaxTotalConnections(httpParams, MAX_TOTAL_CONNECTIONS);
      HttpConnectionParams.setConnectionTimeout(httpParams, CONNECTION_TIMEOUT);
      HttpConnectionParams.setSoTimeout(httpParams, SOCKET_TIMEOUT);

      //            httpParams.setParameter(ConnRoutePNames.DEFAULT_PROXY, new
      // HttpHost("192.168.16.180", 8888, "http"));
      httpParams.setParameter(ClientPNames.COOKIE_POLICY, CookiePolicy.RFC_2109);

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

      ClientConnectionManager connectionManager =
          new ThreadSafeClientConnManager(httpParams, schemeRegistry);

      httpClient = new DefaultHttpClient(connectionManager, httpParams);
    }

    return httpClient;
  }
  /**
   * Creates an HttpClient with the specified userAgent string.
   *
   * @param userAgent the userAgent string
   * @return the client
   */
  public static HttpClient newHttpClient(String userAgent) {
    // AndroidHttpClient is available on all platform releases,
    // but is hidden until API Level 8
    try {
      Class<?> clazz = Class.forName("android.net.http.AndroidHttpClient");
      Method newInstance = clazz.getMethod("newInstance", String.class);
      Object instance = newInstance.invoke(null, userAgent);

      HttpClient client = (HttpClient) instance;

      // ensure we default to HTTP 1.1
      HttpParams params = client.getParams();
      params.setParameter(CoreProtocolPNames.PROTOCOL_VERSION, HttpVersion.HTTP_1_1);

      // AndroidHttpClient sets these two parameters thusly by default:
      // HttpConnectionParams.setSoTimeout(params, 60 * 1000);
      // HttpConnectionParams.setConnectionTimeout(params, 60 * 1000);

      // however it doesn't set this one...
      ConnManagerParams.setTimeout(params, 60 * 1000);

      return client;
    } catch (InvocationTargetException e) {
      throw new RuntimeException(e);
    } catch (ClassNotFoundException e) {
      throw new RuntimeException(e);
    } catch (NoSuchMethodException e) {
      throw new RuntimeException(e);
    } catch (IllegalAccessException e) {
      throw new RuntimeException(e);
    }
  }
Exemplo n.º 11
0
 public HttpUtils configTimeout(int timeout) {
   final HttpParams httpParams = this.httpClient.getParams();
   ConnManagerParams.setTimeout(httpParams, timeout);
   HttpConnectionParams.setSoTimeout(httpParams, timeout);
   HttpConnectionParams.setConnectionTimeout(httpParams, timeout);
   return this;
 }
Exemplo n.º 12
0
 /**
  * Sets maximum limit of parallel connections
  *
  * @param maxConnections maximum parallel connections, must be at least 1
  */
 public void setMaxConnections(int maxConnections) {
   if (maxConnections < 1) maxConnections = DEFAULT_MAX_CONNECTIONS;
   this.maxConnections = maxConnections;
   final HttpParams httpParams = this.httpClient.getParams();
   ConnManagerParams.setMaxConnectionsPerRoute(
       httpParams, new ConnPerRouteBean(this.maxConnections));
 }
Exemplo n.º 13
0
 private static void createHttpClient() {
   client = new DefaultHttpClient();
   final HttpParams params = client.getParams();
   HttpConnectionParams.setConnectionTimeout(params, REQUEST_TIMEOUT);
   HttpConnectionParams.setSoTimeout(params, REQUEST_TIMEOUT);
   ConnManagerParams.setTimeout(params, REQUEST_TIMEOUT);
 }
Exemplo n.º 14
0
  public static synchronized HttpClient getHttpClient() {
    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,
          "Mozilla/5.0(Linux;U;Android 2.2.1;en-us;Nexus One Build.FRG83) "
              + "AppleWebKit/553.1(KHTML,like Gecko) Version/4.0 Mobile Safari/533.1");

      // 从连接池中取连续的超时时间
      ConnManagerParams.setTimeout(params, 1000);
      HttpConnectionParams.setConnectionTimeout(params, 2000);
      HttpConnectionParams.setSoTimeout(params, 4000);

      // 设置我们的HttpClient支持HTTP和HTTPS两种模式
      SchemeRegistry schReg = new SchemeRegistry();
      schReg.register(new Scheme("http", PlainSocketFactory.getSocketFactory(), 80));
      schReg.register(new Scheme("https", SSLSocketFactory.getSocketFactory(), 443));

      // 使用线程安全的连接管理来创建HttpClient
      ClientConnectionManager conMgr = new ThreadSafeClientConnManager(params, schReg);
      customerHttpClient = new DefaultHttpClient(conMgr, params);
    }
    return customerHttpClient;
  }
  private DefaultHttpClient getNewHttpClient() {

    DefaultHttpClient client = null;

    try {
      KeyStore trustStore = KeyStore.getInstance(KeyStore.getDefaultType());
      trustStore.load(null, null);

      SSLSocketFactory sf = new TrustedSSLSocketFactory(trustStore);
      sf.setHostnameVerifier(SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);

      HttpParams params = new BasicHttpParams();

      ConnManagerParams.setMaxTotalConnections(params, 100);

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

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

      ClientConnectionManager ccm = new ThreadSafeClientConnManager(params, registry);

      client = new DefaultHttpClient(ccm, params);
    } catch (Exception e) {
      client = new DefaultHttpClient();
    }

    client = applyTimeout(client);
    return client;
  }
  public void testCloseExpiredConnections() throws Exception {

    HttpParams mgrpar = defaultParams.copy();
    ConnManagerParams.setMaxTotalConnections(mgrpar, 1);

    SingleClientConnManager mgr = createSCCM(mgrpar, null);

    final HttpHost target = getServerHttp();
    final HttpRoute route = new HttpRoute(target, null, false);

    ManagedClientConnection conn = mgr.getConnection(route, null);
    conn.open(route, httpContext, defaultParams);
    mgr.releaseConnection(conn, 100, TimeUnit.MILLISECONDS);

    mgr.closeExpiredConnections();

    conn = mgr.getConnection(route, null);
    assertTrue(conn.isOpen());
    mgr.releaseConnection(conn, 100, TimeUnit.MILLISECONDS);

    Thread.sleep(150);
    mgr.closeExpiredConnections();
    conn = mgr.getConnection(route, null);
    assertFalse(conn.isOpen());

    mgr.shutdown();
  }
Exemplo n.º 17
0
 private static HttpClient getHttpClient() {
   HttpClient httpClient = new DefaultHttpClient();
   final HttpParams params = httpClient.getParams();
   HttpConnectionParams.setConnectionTimeout(params, HTTP_REQUEST_TIMEOUT_MS);
   HttpConnectionParams.setSoTimeout(params, HTTP_REQUEST_TIMEOUT_MS);
   ConnManagerParams.setTimeout(params, HTTP_REQUEST_TIMEOUT_MS);
   return httpClient;
 }
Exemplo n.º 18
0
 /**
  * Set the connection and socket timeout. By default, 10 seconds.
  *
  * @param timeout the connect/socket timeout in milliseconds, at least 1 second
  */
 public void setTimeout(int timeout) {
   if (timeout < 1000) timeout = DEFAULT_SOCKET_TIMEOUT;
   this.timeout = timeout;
   final HttpParams httpParams = this.httpClient.getParams();
   ConnManagerParams.setTimeout(httpParams, this.timeout);
   HttpConnectionParams.setSoTimeout(httpParams, this.timeout);
   HttpConnectionParams.setConnectionTimeout(httpParams, this.timeout);
 }
  // 每次都返回新的HttpClient实例
  public static HttpClient getNewInstance(Context mContext) {
    HttpClient newInstance;

    HttpParams params = new BasicHttpParams();
    HttpProtocolParams.setVersion(params, HttpVersion.HTTP_1_1);
    HttpProtocolParams.setContentCharset(params, HTTP.DEFAULT_CONTENT_CHARSET);
    HttpProtocolParams.setUseExpectContinue(params, true);

    // 自定义三个timeout参数

    /*
     * 1.set a timeout for the connection manager,it defines how long we
     * should wait to get a connection out of the connection pool managed by
     * the connection manager
     */
    ConnManagerParams.setTimeout(params, 5000);

    /*
     * 2.The second timeout value defines how long we should wait to make a
     * connection over the network to the server on the other end
     */
    HttpConnectionParams.setConnectionTimeout(params, TIMEOUT);

    /*
     * 3.we set a socket timeout value to 4 seconds to define how long we
     * should wait to get data back for our request.
     */
    HttpConnectionParams.setSoTimeout(params, TIMEOUT_SOCKET);

    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);

    newInstance = new DefaultHttpClient(conMgr, params);

    switch (checkNetworkType(mContext)) {
      case TYPE_CT_WAP:
        {
          // 通过代理解决中国移动联通GPRS中wap无法访问的问题
          HttpHost proxy = new HttpHost("10.0.0.200", 80, "http");
          newInstance.getParams().setParameter(ConnRoutePNames.DEFAULT_PROXY, proxy);
          Logs.v("当前网络类型为cm_cu_wap,设置代理10.0.0.200访问www");
        }
        break;
      case TYPE_CM_CU_WAP:
        {
          // 通过代理解决中国移动联通GPRS中wap无法访问的问题
          HttpHost proxy = new HttpHost("10.0.0.172", 80, "http");
          newInstance.getParams().setParameter(ConnRoutePNames.DEFAULT_PROXY, proxy);
          Logs.v("当前网络类型为cm_cu_wap,设置代理10.0.0.172访问www");
        }
        break;
    }
    return newInstance;
  }
Exemplo n.º 20
0
 /**
  * Get our single instance of our HttpClient object.
  *
  * @return an HttpClient object with connection parameters set
  */
 private static HttpClient getHttpClient() {
   if (mHttpClient == null) {
     mHttpClient = new DefaultHttpClient();
     final HttpParams params = mHttpClient.getParams();
     HttpConnectionParams.setConnectionTimeout(params, HTTP_TIMEOUT);
     HttpConnectionParams.setSoTimeout(params, HTTP_TIMEOUT);
     ConnManagerParams.setTimeout(params, HTTP_TIMEOUT);
   }
   return mHttpClient;
 }
Exemplo n.º 21
0
  public static HttpClient getThreadSafeClient() {

    HttpParams params = new BasicHttpParams();
    ConnManagerParams.setMaxTotalConnections(params, 100);
    HttpProtocolParams.setVersion(params, HttpVersion.HTTP_1_1);

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

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

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

    return client;
  }
  public static HttpClient newInstance() {
    HttpParams params = new BasicHttpParams();
    // 不自动处理重定向请求
    params.setParameter(ClientPNames.HANDLE_REDIRECTS, false);
    HttpConnectionParams.setStaleCheckingEnabled(params, true);
    HttpConnectionParams.setConnectionTimeout(params, CONNECTION_TIMEOUT);
    HttpConnectionParams.setSoTimeout(params, SOCKET_OPERATION_TIMEOUT);
    HttpConnectionParams.setSocketBufferSize(params, SOCKET_BUFFER_SIZE);
    HttpConnectionParams.setTcpNoDelay(params, true);
    ConnManagerParams.setMaxTotalConnections(params, 50);
    ConnPerRouteBean connPerRoute = new ConnPerRouteBean();
    connPerRoute.setDefaultMaxPerRoute(4);
    ConnManagerParams.setMaxConnectionsPerRoute(params, connPerRoute);

    SchemeRegistry schemeRegistry = new SchemeRegistry();
    schemeRegistry.register(new Scheme("http", PlainSocketFactory.getSocketFactory(), 80));
    SSLSocketFactory socketFactory = SSLSocketFactory.getSocketFactory();
    socketFactory.setHostnameVerifier(SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);
    schemeRegistry.register(new Scheme("https", socketFactory, 443));
    ClientConnectionManager manager = new ThreadSafeClientConnManager(params, schemeRegistry);
    return new DefaultHttpClient(manager, params);
  }
Exemplo n.º 23
0
 /**
  * Configures the httpClient to connect to the URL provided.
  *
  * @param authToken
  */
 private static DefaultHttpClient getHttpClient() {
   DefaultHttpClient httpClient = new DefaultHttpClient();
   final HttpParams params = httpClient.getParams();
   HttpConnectionParams.setConnectionTimeout(params, HTTP_REQUEST_TIMEOUT_MS);
   HttpConnectionParams.setSoTimeout(params, HTTP_REQUEST_TIMEOUT_MS);
   ConnManagerParams.setTimeout(params, HTTP_REQUEST_TIMEOUT_MS);
   HttpClientParams.setRedirecting(params, false);
   HttpClientParams.setCookiePolicy(params, CookiePolicy.BROWSER_COMPATIBILITY);
   httpClient.addRequestInterceptor(new DumpHeadersRequestInterceptor());
   httpClient.addResponseInterceptor(new DumpHeadersResponseInterceptor());
   httpClient.addResponseInterceptor(new CookieQuotesFixerResponseInterceptor());
   return httpClient;
 }
Exemplo n.º 24
0
  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;
  }
Exemplo n.º 25
0
  protected void setupHttpClient() {

    LOG.info("setting up http client");

    BasicHttpParams httpParams = new BasicHttpParams();
    HttpConnectionParams.setSoTimeout(httpParams, 70 * 1000);
    HttpConnectionParams.setConnectionTimeout(httpParams, 10 * 1000);
    ConnManagerParams.setMaxTotalConnections(httpParams, 200);
    ConnPerRoute connPerRoute = new ConnPerRouteBean(400);
    ConnManagerParams.setMaxConnectionsPerRoute(httpParams, connPerRoute);
    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);
    // ThreadSafeClientConnManager cm = new ThreadSafeClientConnManager(httpParams,
    // HttpClientWithKeystore.getSchemeRegistry());
    HttpProtocolParams.setVersion(httpParams, HttpVersion.HTTP_1_1);
    HttpProtocolParams.setContentCharset(httpParams, "utf-8");
    mHttpClient = new HttpClientWithKeystore(cm, httpParams);
    mHttpClient.getParams().setParameter("http.useragent", mConfig.getApplicationName());
    mHttpClient.getParams().setBooleanParameter(CoreProtocolPNames.USE_EXPECT_CONTINUE, false);
    mHttpClient.setReuseStrategy(new NoConnectionReuseStrategy());
  }
Exemplo n.º 26
0
  public void init() {
    if (inited) {
      return;
    }

    // init thread pool
    executor =
        new NimTaskExecutor(
            "NIM_HTTP_TASK_EXECUTOR", new NimTaskExecutor.Config(1, 3, 10 * 1000, true));

    // init HttpClient supporting multi thread access
    HttpParams httpParams = new BasicHttpParams();
    // 设置最大连接数
    ConnManagerParams.setMaxTotalConnections(httpParams, MAX_CONNECTIONS);
    // 设置获取连接的最大等待时间
    ConnManagerParams.setTimeout(httpParams, WAIT_TIMEOUT);
    // 设置每个路由最大连接数
    ConnManagerParams.setMaxConnectionsPerRoute(
        httpParams, new ConnPerRouteBean(MAX_ROUTE_CONNECTIONS));
    // 设置连接超时时间
    HttpConnectionParams.setConnectionTimeout(httpParams, CONNECT_TIMEOUT);
    // 设置读取超时时间
    HttpConnectionParams.setSoTimeout(httpParams, READ_TIMEOUT);

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

    SSLSocketFactory.getSocketFactory().setHostnameVerifier(new AllowAllHostnameVerifier());

    connManager = new ThreadSafeClientConnManager(httpParams, registry);
    client = new DefaultHttpClient(connManager, httpParams);

    uiHandler = new Handler(DemoCache.getContext().getMainLooper());

    inited = true;
  }
Exemplo n.º 27
0
  public Publisher() {

    HttpParams params = new BasicHttpParams();
    ConnManagerParams.setMaxTotalConnections(params, 200);
    ConnPerRouteBean connPerRoute = new ConnPerRouteBean(20);
    connPerRoute.setDefaultMaxPerRoute(50);
    ConnManagerParams.setMaxConnectionsPerRoute(params, connPerRoute);

    SchemeRegistry schemeRegistry = new SchemeRegistry();
    schemeRegistry.register(new Scheme("http", PlainSocketFactory.getSocketFactory(), 80));
    ClientConnectionManager cm = new ThreadSafeClientConnManager(params, schemeRegistry);
    httpClient = new DefaultHttpClient(cm, params);

    httpClient.setKeepAliveStrategy(
        new ConnectionKeepAliveStrategy() {

          public long getKeepAliveDuration(HttpResponse response, HttpContext context) {
            HeaderElementIterator it =
                new BasicHeaderElementIterator(response.headerIterator(HTTP.CONN_KEEP_ALIVE));
            while (it.hasNext()) {
              HeaderElement he = it.nextElement();
              String param = he.getName();
              String value = he.getValue();
              if (value != null && param.equalsIgnoreCase("timeout")) {
                try {
                  return Long.parseLong(value) * 1000;
                } catch (NumberFormatException ignore) {
                }
              }
            }
            // default keepalive is 60 seconds. This is higher than usual
            // since the number of hubs it should be talking to should be
            // small
            return 30 * 1000;
          }
        });
  }
Exemplo n.º 28
0
 public static String IP_Me(boolean format) {
   HttpGet get = new HttpGet("http://whois.pconline.com.cn/ipJson.jsp");
   Header[] headers = new Header[4];
   headers[0] = new BasicHeader("Accept", "Application/json;q=0.9,*/*;q=0.8");
   headers[1] = new BasicHeader("Accept-Charset", "utf-8");
   headers[2] = new BasicHeader("Content-Type", "application/x-www-form-urlencoded");
   headers[3] =
       new BasicHeader(
           "User-Agent",
           "Mozilla/5.0 (Windows NT 5.1) AppleWebKit/535.11"
               + " (KHTML, like Gecko) Chrome/17.0.963.56 Safari/535.11");
   get.setHeaders(headers);
   BasicHttpParams httpParams = new BasicHttpParams();
   HttpConnectionParams.setConnectionTimeout(httpParams, 30000);
   HttpConnectionParams.setSoTimeout(httpParams, 30000);
   ConnManagerParams.setTimeout(httpParams, 30000);
   try {
     HttpResponse httpResponse = new DefaultHttpClient(httpParams).execute(get);
     StatusLine statusLine = httpResponse.getStatusLine();
     int statusCode = statusLine.getStatusCode();
     if (statusCode == 200) {
       String json = EntityUtils.toString(httpResponse.getEntity(), "utf-8");
       if (!TextUtils.isEmpty(json)) {
         json = json.substring(json.indexOf("{\""), json.indexOf(");")).trim();
         JSONObject obj = new JSONObject(json);
         if (format) {
           json = obj.getString("ip").replace('.', '_');
           // json += "-" + obj.getString("pro");
           // json += "-" + obj.getString("city");
           json += "-" + obj.getString("addr").replace(" ", "");
           // obj.getString("regionNames");
         } else {
           json = obj.getString("ip");
           // json += " " + obj.getString("pro");
           // json += " " + obj.getString("city");
           json += " " + obj.getString("addr");
           // obj.getString("regionNames");
         }
       }
       return json;
     } else {
       return null;
     }
   } catch (Exception e) {
     return null;
   }
 }
  private HttpClient createHttpClient() {
    HttpParams params = new BasicHttpParams();
    HttpProtocolParams.setVersion(params, HttpVersion.HTTP_1_1);
    HttpProtocolParams.setContentCharset(params, HTTP.DEFAULT_CONTENT_CHARSET);
    HttpProtocolParams.setUseExpectContinue(params, true);

    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);

    return new DefaultHttpClient(conMgr, params);
  }
  /** Tests that SCM can still connect to the same host after a connection was aborted. */
  public void testOpenAfterAbort() throws Exception {
    HttpParams mgrpar = defaultParams.copy();
    ConnManagerParams.setMaxTotalConnections(mgrpar, 1);

    SingleClientConnManager mgr = createSCCM(mgrpar, null);

    final HttpHost target = getServerHttp();
    final HttpRoute route = new HttpRoute(target, null, false);

    ManagedClientConnection conn = mgr.getConnection(route, null);
    assertTrue(conn instanceof AbstractClientConnAdapter);
    ((AbstractClientConnAdapter) conn).abortConnection();

    conn = mgr.getConnection(route, null);
    assertFalse("connection should have been closed", conn.isOpen());
    conn.open(route, httpContext, defaultParams);

    mgr.releaseConnection(conn, -1, null);
    mgr.shutdown();
  }