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;
 }
  private static HttpClient getNewHttpClient() {
    try {
      KeyStore trustStore = KeyStore.getInstance(KeyStore.getDefaultType());
      trustStore.load(null, null);

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

      HttpParams params = new BasicHttpParams();
      HttpProtocolParams.setVersion(params, HttpVersion.HTTP_1_1);
      HttpProtocolParams.setContentCharset(params, HTTP.UTF_8);
      HttpConnectionParams.setConnectionTimeout(params, 10000);
      HttpConnectionParams.setSoTimeout(params, 20000);

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

      return new DefaultHttpClient(ccm, params);
    } catch (Exception e) {
      return new DefaultHttpClient();
    }
  }
Exemple #3
0
  /**
   * Create HttpClient based on HTTP or HTTPS protocol that is parsed from url parameter. With HTTPS
   * protocol, we accept all SSL certificates.
   *
   * @param url
   * @param params
   * @return
   */
  protected HttpClient createHttpClient(String url, HttpParams params) {
    if ((url.toLowerCase().startsWith("https"))) {
      // HTTPS process
      try {

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

        SSLSocketFactory sf = new FMySSLSocketFactory(trustStore);
        sf.setHostnameVerifier(SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);
        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);

        return new DefaultHttpClient(ccm, params);
      } catch (Exception e) {
        return new DefaultHttpClient(params);
      }
    } else {
      // HTTP process
      return new DefaultHttpClient(params);
    }
  }
Exemple #4
0
 public static HttpClient getNewHttpClient() {
   try {
     KeyStore trustStore = KeyStore.getInstance(KeyStore.getDefaultType());
     trustStore.load(null, null);
     SSLSocketFactory sf = new SSLSocketFactoryEx(trustStore);
     sf.setHostnameVerifier(SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);
     HttpParams params = new BasicHttpParams();
     HttpProtocolParams.setVersion(params, HttpVersion.HTTP_1_1);
     HttpProtocolParams.setContentCharset(params, HTTP.UTF_8);
     HttpProtocolParams.setUserAgent(
         params,
         "Mozilla/5.0 (Windows; Windows NT 6.3) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/43.0.2357.65 Safari/537.36");
     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);
     @SuppressWarnings("resource")
     DefaultHttpClient httpClient = new DefaultHttpClient(ccm, params);
     httpClient.setCookieStore(new BasicCookieStore());
     httpClient.getParams().setParameter(CoreConnectionPNames.CONNECTION_TIMEOUT, 5000);
     httpClient.getParams().setParameter(CoreConnectionPNames.SO_TIMEOUT, 5000);
     return new DefaultHttpClient(ccm, params);
   } catch (Exception e) {
     return new DefaultHttpClient();
   }
 }
  protected @Nonnull HttpClient getClient(String url, boolean multipart) throws InternalException {
    ProviderContext ctx = provider.getContext();

    if (ctx == null) {
      throw new InternalException("No context was specified for this request");
    }
    boolean ssl = url.startsWith("https");
    HttpParams params = new BasicHttpParams();

    HttpProtocolParams.setVersion(params, HttpVersion.HTTP_1_1);
    if (!multipart) {
      HttpProtocolParams.setContentCharset(params, HTTP.UTF_8);
    }
    HttpProtocolParams.setUserAgent(params, "Dasein Cloud");

    Properties p = ctx.getCustomProperties();

    if (p != null) {
      String proxyHost = p.getProperty("proxyHost");
      String proxyPort = p.getProperty("proxyPort");

      if (proxyHost != null) {
        int port = 0;

        if (proxyPort != null && proxyPort.length() > 0) {
          port = Integer.parseInt(proxyPort);
        }
        params.setParameter(
            ConnRoutePNames.DEFAULT_PROXY, new HttpHost(proxyHost, port, ssl ? "https" : "http"));
      }
    }
    return new DefaultHttpClient(params);
  }
Exemple #6
0
 private static DefaultHttpClient createHttpsClient() {
   DefaultHttpClient defaulthttpclient = new DefaultHttpClient();
   DefaultHttpClient defaulthttpclient1;
   try {
     KeyStore keystore = KeyStore.getInstance(KeyStore.getDefaultType());
     keystore.load(null, null);
     CustomSSLSocketFactory customsslsocketfactory = new CustomSSLSocketFactory(keystore);
     customsslsocketfactory.setHostnameVerifier(SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);
     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);
     SchemeRegistry schemeregistry = new SchemeRegistry();
     schemeregistry.register(new Scheme("http", PlainSocketFactory.getSocketFactory(), 80));
     schemeregistry.register(new Scheme("https", customsslsocketfactory, 443));
     defaulthttpclient1 =
         new DefaultHttpClient(
             new ThreadSafeClientConnManager(basichttpparams, schemeregistry), basichttpparams);
     defaulthttpclient1
         .getCredentialsProvider()
         .setCredentials(
             new AuthScope(null, -1), new UsernamePasswordCredentials("admin", "admin"));
     defaulthttpclient = defaulthttpclient1;
   } catch (Exception e) {
     e.printStackTrace();
   }
   return defaulthttpclient;
 }
Exemple #7
0
  static {
    httpClient = new DefaultHttpClient();
    HttpParams params = httpClient.getParams();

    // set the time out of the connection/ socket. and the cache size
    HttpConnectionParams.setConnectionTimeout(params, 30 * 1000);
    HttpConnectionParams.setSoTimeout(params, 30 * 1000);
    HttpConnectionParams.setSocketBufferSize(params, 8192);

    // set the connection manager factory
    params.setParameter(
        ClientPNames.CONNECTION_MANAGER_FACTORY,
        new ClientConnectionManagerFactory() {
          public ClientConnectionManager newInstance(
              HttpParams params, SchemeRegistry schemeRegistry) {
            return new ThreadSafeClientConnManager(params, schemeRegistry);
          }
        });

    // set the redirect, default is true
    HttpClientParams.setRedirecting(params, true);

    // set the client verion
    HttpProtocolParams.setVersion(params, HttpVersion.HTTP_1_1);
    // set user-agent
    HttpProtocolParams.setUserAgent(params, "eoeWIKI_Android/0.9");
    // set the charset
    HttpProtocolParams.setHttpElementCharset(params, HTTP.UTF_8);
    HttpProtocolParams.setContentCharset(params, HTTP.UTF_8);
    // set not activate Expect:100-Continue
    HttpProtocolParams.setUseExpectContinue(params, false);

    // set the version of the cookie
    params.setParameter(ClientPNames.COOKIE_POLICY, CookiePolicy.RFC_2965);
  }
Exemple #8
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;
                }
              }
            }
          }
        });
  }
  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;
  }
  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;
  }
    /**
     * Static method to initialize HTTP client. Notice the double instance == null check. By
     * checking in and outside of the synchronization, this method is threadsafe. It ensures the
     * singleton is only instantiated once.
     *
     * @return
     */
    public HttpClient getInstance() {
      if (INSTANCE == null) {
        synchronized (HttpConnectionManager.class) {
          if (INSTANCE == null) {
            final HttpParams params = new BasicHttpParams();
            final SchemeRegistry registry = new SchemeRegistry();
            final SSLSocketFactory sslSocketFactory = SSLSocketFactory.getSocketFactory();

            HttpProtocolParams.setVersion(params, HttpVersion.HTTP_1_1);
            HttpProtocolParams.setContentCharset(params, "utf-8");
            HttpProtocolParams.setUserAgent(params, "Basedroid");

            sslSocketFactory.setHostnameVerifier(
                SSLSocketFactory.BROWSER_COMPATIBLE_HOSTNAME_VERIFIER);

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

            final ClientConnectionManager manager =
                new ThreadSafeClientConnManager(params, registry);
            INSTANCE = new DefaultHttpClient(manager, params);
          }
        }
      }
      return INSTANCE;
    }
  public void post(FileEntity fileEntity) throws IOException {
    HttpHost httpHost = new HttpHost(uri.getHost(), uri.getPort());
    HttpPost httpPost = new HttpPost(uri);
    httpPost.setEntity(fileEntity);

    HttpParams params = httpPost.getParams();
    HttpConnectionParams.setConnectionTimeout(params, timeout);
    HttpConnectionParams.setSoTimeout(params, timeout);
    HttpConnectionParams.setStaleCheckingEnabled(params, true);
    HttpConnectionParams.setTcpNoDelay(params, true);
    HttpClientParams.setRedirecting(params, true);
    HttpProtocolParams.setUseExpectContinue(params, false);
    HttpProtocolParams.setUserAgent(params, DEFAULT_USER_AGENT);

    try {

      HttpResponse response = DEFAULT_HTTP_CLIENT.execute(httpHost, httpPost);

      if (response.getStatusLine().getStatusCode() < 200
          || response.getStatusLine().getStatusCode() >= 300)
        throw new IOException(
            "bad status code, upload file " + response.getStatusLine().getStatusCode());

    } catch (IOException e) {
      throw e;
    } catch (Exception e) {
      throw new IOException("Http error: " + e.getMessage());
    } finally {
      //
    }
  }
  public HttpClient4Sender() {
    clientParams.setParameter(
        CoreConnectionPNames.CONNECTION_TIMEOUT, DEFAULT_CONNECTION_TIMEOUT_MILLISECONDS);
    clientParams.setParameter(CoreConnectionPNames.SO_TIMEOUT, DEFAULT_READ_TIMEOUT_MILLISECONDS);

    HttpProtocolParams.setVersion(clientParams, HttpVersion.HTTP_1_1);
    HttpProtocolParams.setContentCharset(clientParams, "UTF-8");
  }
  /** LDR4JのHTTPクライアントを構築します。 */
  protected AbstractLDRHttpClient() {
    HttpParams params = new BasicHttpParams();
    HttpProtocolParams.setVersion(params, HttpVersion.HTTP_1_1);
    HttpProtocolParams.setContentCharset(params, HTTP.UTF_8);
    HttpProtocolParams.setUserAgent(params, LDR4J.TITLE + "/" + LDR4J.VERSION);

    httpClient = new DefaultHttpClient(params);
  }
    @Override
    protected String doInBackground(String... params) {
      // TODO Auto-generated method stub

      String response = null;

      try {

        SSLSocketFactory sslFactory =
            new CustomSSLSocketFactory(
                CustomSSLSocketFactory.getKeyStoreForCertificate(
                    getApplicationContext().getResources().getAssets().open("new_server.crt")));
        // sslFactory.setHostnameVerifier(SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);
        // to be used in case of bypassing certificates

        // Enable HTTP parameters */
        HttpParams params4 = new BasicHttpParams();
        HttpProtocolParams.setVersion(params4, HttpVersion.HTTP_1_1);
        HttpProtocolParams.setContentCharset(params4, HTTP.UTF_8);

        // Register the HTTP and HTTPS Protocols. For HTTPS, register
        // our custom SSL Factory object.
        SchemeRegistry registry = new SchemeRegistry();
        registry.register(new Scheme("http", PlainSocketFactory.getSocketFactory(), 80));
        registry.register(new Scheme("https", sslFactory, 443));

        // Create a new connection manager using the newly created
        // registry and then create a new HTTP client
        // using this connection manager
        ClientConnectionManager ccm = new ThreadSafeClientConnManager(params4, registry);
        DefaultHttpClient client = new DefaultHttpClient(ccm, params4);
        HttpPost httppostreq = new HttpPost(params[0]);
        StringEntity se = new StringEntity(params[1]);
        se.setContentType("application/json;charset=UTF-8");
        se.setContentEncoding(new BasicHeader(HTTP.CONTENT_TYPE, "application/json;charset=UTF-8"));
        httppostreq.setEntity(se);
        HttpResponse httpresponse = client.execute(httppostreq);
        httpresponse.getStatusLine().getStatusCode();

        HttpEntity httpEntity = httpresponse.getEntity();
        response = EntityUtils.toString(httpEntity);
      } catch (UnsupportedEncodingException e) {
        e.printStackTrace();
      } catch (ClientProtocolException e) {
        e.printStackTrace();
      } catch (SSLHandshakeException e) {
        e.printStackTrace();
      } catch (SSLException e) {
        e.printStackTrace();
      } catch (IOException e) {
        // e.printStackTrace();
        System.out.println(e);
      } catch (Exception e) {
        e.printStackTrace();
      }

      return response;
    }
Exemple #16
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>();
  }
  // 每次都返回新的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;
  }
 private FabHttpConnection()
 {
   this.params.setBooleanParameter("http.protocol.expect-continue", false);
   this.params.setBooleanParameter("http.connection.stalecheck", false);
   this.params.setIntParameter("http.socket.buffer-size", 8192);
   HttpProtocolParams.setVersion(this.params, HttpVersion.HTTP_1_1);
   HttpProtocolParams.setContentCharset(this.params, "UTF-8");
   this.client = new DefaultHttpClient(this.params);
   this.client.getConnectionManager().closeExpiredConnections();
 }
 static {
   HttpParams params = new BasicHttpParams();
   HttpProtocolParams.setVersion(params, HttpVersion.HTTP_1_1);
   HttpProtocolParams.setContentCharset(params, "UTF-8");
   HttpProtocolParams.setUserAgent(params, WeaveConstants.USER_AGENT);
   HttpProtocolParams.setUseExpectContinue(params, false);
   //    params.setParameter(HttpProtocolParams.USE_EXPECT_CONTINUE, false);
   params.setParameter(ConnManagerPNames.MAX_TOTAL_CONNECTIONS, 30);
   params.setParameter(ConnManagerPNames.MAX_CONNECTIONS_PER_ROUTE, new ConnPerRouteBean(30));
   sm_httpParams = params;
 }
 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);
   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);
 }
  private static HttpClient getHttpClient() {

    HttpParams httpParameters = new BasicHttpParams();
    HttpProtocolParams.setContentCharset(httpParameters, HTTP.UTF_8);
    HttpProtocolParams.setHttpElementCharset(httpParameters, HTTP.UTF_8);
    mHttpClient = new DefaultHttpClient(httpParameters);
    mHttpClient.getParams().setParameter("http.protocol.version", HttpVersion.HTTP_1_1);
    mHttpClient.getParams().setParameter("http.socket.timeout", new Integer(2000));
    mHttpClient.getParams().setParameter("http.protocol.content-charset", HTTP.UTF_8);
    httpParameters.setBooleanParameter("http.protocol.expect-continue", false);

    return mHttpClient;
  }
  public byte[] post(String postBody, String contentType) throws IOException {
    HttpHost httpHost = new HttpHost(uri.getHost(), uri.getPort());
    HttpPost httpPost = new HttpPost(uri);

    StringEntity stringEntity = new StringEntity(postBody);
    httpPost.setHeader("Accept", "application/json");
    httpPost.setHeader("Content-type", "application/json");
    httpPost.setEntity(stringEntity);

    HttpParams params = httpPost.getParams();
    HttpConnectionParams.setConnectionTimeout(params, timeout);
    HttpConnectionParams.setSoTimeout(params, timeout);
    HttpConnectionParams.setStaleCheckingEnabled(params, true);
    HttpConnectionParams.setTcpNoDelay(params, true);
    HttpClientParams.setRedirecting(params, true);
    HttpProtocolParams.setUseExpectContinue(params, false);
    HttpProtocolParams.setUserAgent(params, DEFAULT_USER_AGENT);

    ByteArrayOutputStream baos = new ByteArrayOutputStream();

    try {

      HttpResponse response = DEFAULT_HTTP_CLIENT.execute(httpHost, httpPost);

      if (response.getStatusLine().getStatusCode() < 200
          || response.getStatusLine().getStatusCode() >= 300)
        throw new IOException(
            "bad status code, upload file " + response.getStatusLine().getStatusCode());

      if (response.getEntity() != null) {
        response.getEntity().writeTo(baos);
      }

      body = baos.toByteArray();

      if (body == null || body.length == 0) {
        throw new IOException("invalid response");
      }

      return body;
    } catch (IOException e) {
      throw e;
    } catch (Exception e) {
      throw new IOException("Http error: " + e.getMessage());
    } finally {
      try {
        baos.close();
      } catch (IOException e) {
      }
    }
  }
  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;
  }
 /* constructor */
 public JsonFeedGetter(Context c, int mode) {
   mode_ = mode;
   context_ = c;
   final HttpParams httpParams = new BasicHttpParams();
   HttpProtocolParams.setVersion(httpParams, HttpVersion.HTTP_1_1);
   HttpProtocolParams.setContentCharset(httpParams, "UTF-8");
   HttpConnectionParams.setConnectionTimeout(httpParams, connection_Timeout);
   HttpConnectionParams.setSoTimeout(httpParams, connection_Timeout);
   final SchemeRegistry schemeRegistry = new SchemeRegistry();
   schemeRegistry.register(new Scheme("http", PlainSocketFactory.getSocketFactory(), 80));
   httpClient_ =
       new DefaultHttpClient(
           new ThreadSafeClientConnManager(httpParams, schemeRegistry), httpParams);
 }
  public void save(File file, HttpFetcherListener listener) throws IOException {
    HttpHost httpHost = new HttpHost(uri.getHost(), uri.getPort());
    HttpGet httpGet = new HttpGet(uri);
    httpGet.addHeader("Connection", "close");

    HttpParams params = httpGet.getParams();
    HttpConnectionParams.setConnectionTimeout(params, timeout);
    HttpConnectionParams.setSoTimeout(params, timeout);
    HttpConnectionParams.setStaleCheckingEnabled(params, true);
    HttpConnectionParams.setTcpNoDelay(params, true);
    HttpClientParams.setRedirecting(params, true);
    HttpProtocolParams.setUseExpectContinue(params, false);
    HttpProtocolParams.setUserAgent(params, userAgent);

    FileOutputStream out = null;

    int statusCode = -1;
    Map<String, String> headers = null;

    try {

      out = new FileOutputStream(file);

      HttpResponse response = DEFAULT_HTTP_CLIENT.execute(httpHost, httpGet);

      statusCode = response.getStatusLine().getStatusCode();
      headers = mapHeaders(response.headerIterator());

      if (statusCode < 200 || statusCode >= 300) {
        throw new IOException("bad status code, downloading file " + statusCode);
      }

      if (response.getEntity() != null) {
        writeEntity(response.getEntity(), out, listener);
      }

      if (listener != null) {
        listener.onSuccess(new byte[0]);
      }

    } catch (Throwable e) {
      if (listener != null) {
        listener.onError(e, statusCode, headers);
      }
      Log.e(TAG, "Error downloading from: " + uri + ", e: " + e.getMessage());
    } finally {
      IOUtils.closeQuietly(out);
    }
  }
 /** 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;
 }
Exemple #27
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);
 }
  private static AndroidHttpClient createHttpClient(Context context) {

    // Get Shared Preferences and User Defined User Agent for MMS
    SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(context);
    mUserAgent = prefs.getString(MessagingPreferenceActivity.USER_AGENT, MmsConfig.getUserAgent());
    if (mUserAgent == null || mUserAgent.equals("") || mUserAgent.equals("default")) {
      mUserAgent = MmsConfig.getUserAgent();
    } else if (mUserAgent.equals("custom")) {
      mUserAgent =
          prefs.getString(MessagingPreferenceActivity.USER_AGENT_CUSTOM, MmsConfig.getUserAgent());
    }

    AndroidHttpClient client = AndroidHttpClient.newInstance(mUserAgent);

    HttpParams params = client.getParams();
    HttpProtocolParams.setContentCharset(params, "UTF-8");

    // set the socket timeout
    int soTimeout = MmsConfig.getHttpSocketTimeout();

    if (Log.isLoggable(LogTag.TRANSACTION, Log.DEBUG)) {
      Log.d(
          TAG,
          "[HttpUtils] createHttpClient w/ socket timeout "
              + soTimeout
              + " ms, "
              + ", UA="
              + mUserAgent);
    }
    HttpConnectionParams.setSoTimeout(params, soTimeout);
    return client;
  }
  /**
   * Create a new HttpClient with reasonable defaults (which you can update).
   *
   * @param userAgent to report in your HTTP requests.
   * @return FailfastHttpClient for you to use for all your requests.
   */
  public static FailfastHttpClient newInstance(String userAgent) {
    HttpParams params = new BasicHttpParams();

    // Turn off stale checking.  Our connections break all the time anyway,
    // and it's not worth it to pay the penalty of checking every time.
    HttpConnectionParams.setStaleCheckingEnabled(params, false);

    // Default connection and socket timeout of 10 seconds.  Tweak to taste.
    HttpConnectionParams.setConnectionTimeout(params, CONNECT_TIMEOUT);
    HttpConnectionParams.setSoTimeout(params, READ_TIMEOUT);
    HttpConnectionParams.setSocketBufferSize(params, 8192);

    // Don't handle redirects -- return them to the caller.  Our code
    // often wants to re-POST after a redirect, which we must do ourselves.
    HttpClientParams.setRedirecting(params, false);

    // Set the specified user agent and register standard protocols.
    if (userAgent != null) HttpProtocolParams.setUserAgent(params, userAgent);

    SchemeRegistry schemeRegistry = new SchemeRegistry();
    schemeRegistry.register(new Scheme("http", PlainSocketFactory.getSocketFactory(), 80));
    ClientConnectionManager manager = new HackThreadSafeClientConnManager(params, schemeRegistry);

    // We use a factory method to modify superclass initialization
    // parameters without the funny call-a-static-method dance.
    return new FailfastHttpClient(manager, params);
  }
  @Override
  protected HttpParams createHttpParams() {
    HttpParams params = new SyncBasicHttpParams();
    HttpProtocolParams.setVersion(params, HttpVersion.HTTP_1_1);
    HttpProtocolParams.setContentCharset(params, HTTP.DEFAULT_CONTENT_CHARSET);
    HttpConnectionParams.setTcpNoDelay(params, true);
    HttpConnectionParams.setSocketBufferSize(params, 8192);

    // determine the release version from packaged version info
    final VersionInfo vi =
        VersionInfo.loadVersionInfo("org.apache.http.client", getClass().getClassLoader());
    final String release = (vi != null) ? vi.getRelease() : VersionInfo.UNAVAILABLE;
    HttpProtocolParams.setUserAgent(params, "Apache-HttpClient/" + release + " (java 1.5)");

    return params;
  }