Example #1
0
  public static String httpGetSSL(final String exist, String database, String android_id)
      throws IOException, HttpHostConnectException, ConnectException {
    String getUrl = "https://" + exist + ":50001/exist/rest/db/calendar/" + android_id + ".xml";
    LogHelper.logV(c, "httpGetSSL: " + getUrl);

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

    DefaultHttpClient httpClient = new DefaultHttpClient();
    HttpParams params = httpClient.getParams();
    ClientConnectionManager ccm = new SingleClientConnManager(params, schemeRegistry);

    httpClient =
        new DefaultHttpClient(new ThreadSafeClientConnManager(params, schemeRegistry), params);
    httpClient.setRedirectHandler(new DefaultRedirectHandler());

    HttpGet get = new HttpGet(getUrl);

    get.setHeader("Location", database + ":50082");
    get.setHeader("Connection", "close");

    HttpResponse response = httpClient.execute(get);

    HttpEntity httpEntity = response.getEntity();

    return EntityUtils.toString(httpEntity);
  }
Example #2
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;
  }
  @Override
  protected ClientConnectionManager createClientConnectionManager() {
    SchemeRegistry registry = new SchemeRegistry();
    registry.register(new Scheme("http", 80, PlainSocketFactory.getSocketFactory()));
    registry.register(new Scheme("https", 443, SSLSocketFactory.getSocketFactory()));

    ClientConnectionManager connManager = null;
    HttpParams params = getParams();

    ClientConnectionManagerFactory factory = null;

    String className =
        (String) params.getParameter(ClientPNames.CONNECTION_MANAGER_FACTORY_CLASS_NAME);
    if (className != null) {
      try {
        Class<?> clazz = Class.forName(className);
        factory = (ClientConnectionManagerFactory) clazz.newInstance();
      } catch (ClassNotFoundException ex) {
        throw new IllegalStateException("Invalid class name: " + className);
      } catch (IllegalAccessException ex) {
        throw new IllegalAccessError(ex.getMessage());
      } catch (InstantiationException ex) {
        throw new InstantiationError(ex.getMessage());
      }
    }
    if (factory != null) {
      connManager = factory.newInstance(params, registry);
    } else {
      connManager = new SingleClientConnManager(registry);
    }

    return connManager;
  }
    /**
     * 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;
    }
Example #5
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;
  }
Example #6
0
  /**
   * Create a new HttpClient with reasonable defaults (which you can update).
   *
   * @param userAgent to report in your HTTP requests.
   * @return AndroidHttpClient for you to use for all your requests.
   */
  public static AndroidHttpClient 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 20 seconds.  Tweak to taste.
    HttpConnectionParams.setConnectionTimeout(params, 20 * 1000);
    HttpConnectionParams.setSoTimeout(params, 20 * 1000);
    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.
    HttpProtocolParams.setUserAgent(params, userAgent);
    SchemeRegistry schemeRegistry = new SchemeRegistry();
    schemeRegistry.register(new Scheme("http", PlainSocketFactory.getSocketFactory(), 80));
    schemeRegistry.register(new Scheme("https", SSLSocketFactory.getSocketFactory(), 443));
    ClientConnectionManager manager = new ThreadSafeClientConnManager(params, schemeRegistry);

    // We use a factory method to modify superclass initialization
    // parameters without the funny call-a-static-method dance.
    return new AndroidHttpClient(manager, params);
  }
Example #7
0
  private static SSLSocketFactory getSocketFactory(Boolean d) {
    // Enable debug mode to ignore all certificates
    if (DEBUG) {
      KeyStore trustStore;
      try {
        trustStore = KeyStore.getInstance(KeyStore.getDefaultType());
        trustStore.load(null, null);
        SSLSocketFactory sf = new DebugSSLSocketFactory(trustStore);
        sf.setHostnameVerifier(SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);
        return sf;

      } catch (KeyStoreException e2) {
        // TODO Auto-generated catch block
        e2.printStackTrace();
      } catch (NoSuchAlgorithmException e3) {
        // TODO Auto-generated catch block
        e3.printStackTrace();
      } catch (CertificateException e3) {
        // TODO Auto-generated catch block
        e3.printStackTrace();
      } catch (IOException e3) {
        // TODO Auto-generated catch block
        e3.printStackTrace();
      } catch (KeyManagementException e2) {
        // TODO Auto-generated catch block
        e2.printStackTrace();
      } catch (UnrecoverableKeyException e2) {
        // TODO Auto-generated catch block
        e2.printStackTrace();
      }
    }

    return SSLSocketFactory.getSocketFactory();
  }
  /**
   * Returns default instance of SchemeRegistry
   *
   * @param fixNoHttpResponseException Whether to fix or not issue, by ommiting SSL verification
   * @param httpPort HTTP port to be used, must be greater than 0
   * @param httpsPort HTTPS port to be used, must be greater than 0
   */
  private static SchemeRegistry getDefaultSchemeRegistry(
      boolean fixNoHttpResponseException, int httpPort, int httpsPort) {
    if (fixNoHttpResponseException) {
      Log.d(LOG_TAG, "Beware! Using the fix is insecure, as it doesn't verify SSL certificates.");
    }

    if (httpPort < 1) {
      httpPort = 80;
      Log.d(LOG_TAG, "Invalid HTTP port number specified, defaulting to 80");
    }

    if (httpsPort < 1) {
      httpsPort = 443;
      Log.d(LOG_TAG, "Invalid HTTPS port number specified, defaulting to 443");
    }

    // Fix to SSL flaw in API < ICS
    // See https://code.google.com/p/android/issues/detail?id=13117
    SSLSocketFactory sslSocketFactory;
    if (fixNoHttpResponseException) sslSocketFactory = MySSLSocketFactory.getFixedSocketFactory();
    else sslSocketFactory = SSLSocketFactory.getSocketFactory();

    SchemeRegistry schemeRegistry = new SchemeRegistry();
    schemeRegistry.register(new Scheme("http", PlainSocketFactory.getSocketFactory(), httpPort));
    schemeRegistry.register(new Scheme("https", sslSocketFactory, httpsPort));

    return schemeRegistry;
  }
  /**
   * Creates SSLSockets that don't use the SSLv2Hello protocol. This is primarily to work around
   * TripIt.coms SSL... quirks.
   */
  private static final class CustomSSLSocketFactory implements LayeredSocketFactory {
    private final LayeredSocketFactory factory = SSLSocketFactory.getSocketFactory();
    private final String protocol;

    public CustomSSLSocketFactory(String protocol) {
      this.protocol = protocol;
    }

    public Socket createSocket() throws IOException {
      SSLSocket socket = (SSLSocket) factory.createSocket();
      socket.setEnabledProtocols(new String[] {protocol});
      return socket;
    }

    public Socket connectSocket(
        Socket sock,
        String host,
        int port,
        InetAddress localAddress,
        int localPort,
        HttpParams params)
        throws IOException, UnknownHostException, ConnectTimeoutException {
      return factory.connectSocket(sock, host, port, localAddress, localPort, params);
    }

    public boolean isSecure(Socket sock) throws IllegalArgumentException {
      return factory.isSecure(sock);
    }

    public Socket createSocket(Socket socket, String host, int port, boolean autoClose)
        throws IOException, UnknownHostException {
      return factory.createSocket(socket, host, port, autoClose);
    }
  }
  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;
  }
Example #11
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 static ClientConnectionManager getClientConnectionManager() {
   SchemeRegistry registry = new SchemeRegistry();
   registry.register(new Scheme("http", 80, PlainSocketFactory.getSocketFactory()));
   registry.register(new Scheme("https", 443, SSLSocketFactory.getSocketFactory()));
   ThreadSafeClientConnManager cm = new ThreadSafeClientConnManager(registry);
   cm.setMaxTotal(2000);
   cm.setDefaultMaxPerRoute(2000);
   return cm;
 }
Example #14
0
 public static final HttpClient theThreadSafeHttpClient() {
   SchemeRegistry registry = new SchemeRegistry();
   registry.register(new Scheme("http", 80, PlainSocketFactory.getSocketFactory()));
   registry.register(new Scheme("https", 443, SSLSocketFactory.getSocketFactory()));
   ClientConnectionManager connectionManager = new ThreadSafeClientConnManager(registry);
   HttpParams params = new BasicHttpParams();
   HttpConnectionParams.setConnectionTimeout(params, DEFAULT_TIMEOUT);
   HttpClient client = new DefaultHttpClient(connectionManager, params);
   return client;
 }
 public TrustedSocketFactory(String host, boolean secure)
     throws NoSuchAlgorithmException, KeyManagementException {
   SSLContext sslContext = SSLContext.getInstance("TLS");
   sslContext.init(
       null, new TrustManager[] {TrustManagerFactory.get(host, secure)}, new SecureRandom());
   mSocketFactory = sslContext.getSocketFactory();
   mSchemeSocketFactory = org.apache.http.conn.ssl.SSLSocketFactory.getSocketFactory();
   mSchemeSocketFactory.setHostnameVerifier(
       org.apache.http.conn.ssl.SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);
 }
Example #16
0
 private static SocketFactory createSocketFactory(boolean allowInvalidCerts) {
   SocketFactory sslSocketFactory;
   if (allowInvalidCerts) {
     sslSocketFactory = new WeaveSSLSocketFactory();
   } else {
     sslSocketFactory = SSLSocketFactory.getSocketFactory();
     ((SSLSocketFactory) sslSocketFactory).setHostnameVerifier(new WeaveHostnameVerifier());
   }
   return sslSocketFactory;
 }
 /**
  * Returns a SSlSocketFactory which trusts all certificates
  *
  * @return SSLSocketFactory
  */
 public static SSLSocketFactory getFixedSocketFactory() {
   SSLSocketFactory socketFactory;
   try {
     socketFactory = new MySSLSocketFactory(getKeystore());
     socketFactory.setHostnameVerifier(SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);
   } catch (Throwable t) {
     t.printStackTrace();
     socketFactory = SSLSocketFactory.getSocketFactory();
   }
   return socketFactory;
 }
Example #18
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>();
  }
Example #19
0
 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);
 }
  /**
   * Main constructor class for setting up the client that the specific Places/Context clients
   * extend from.
   */
  protected AbstractSimpleGeoClient() {

    HttpParams params = new BasicHttpParams();
    HttpProtocolParams.setUseExpectContinue(params, false);
    SchemeRegistry schemeRegistry = new SchemeRegistry();
    schemeRegistry.register(new Scheme("https", PORT, SSLSocketFactory.getSocketFactory()));
    ThreadSafeClientConnManager connManager = new ThreadSafeClientConnManager(schemeRegistry);

    this.httpClient = new OAuthHttpClient(connManager, params);
    this.threadExecutor = new RequestThreadPoolExecutor("SimpleGeoClient");
    endpoints.put("features", "1.0/features/%s.json");
    endpoints.put("annotations", "1.0/features/%s/annotations.json");
  }
Example #21
0
  @Override
  public void onCreate() {
    super.onCreate();
    // MobclickAgent.openActivityDurationTrack(false);

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

    mContext = this;

    initDatabase();
    initImageLoader();
    initAppConfig();
  }
 public static org.apache.http.conn.ssl.SSLSocketFactory getFixedSocketFactory()
 {
   try
   {
     MySSLSocketFactory localMySSLSocketFactory = new MySSLSocketFactory(getKeystore());
     localMySSLSocketFactory.setHostnameVerifier(org.apache.http.conn.ssl.SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);
     return localMySSLSocketFactory;
   }
   catch (Throwable localThrowable)
   {
     localThrowable.printStackTrace();
   }
   return org.apache.http.conn.ssl.SSLSocketFactory.getSocketFactory();
 }
  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;
  }
Example #24
0
  /**
   * XMLRPCClient constructor. Creates new instance based on server URI (Code contributed by sgayda2
   * from issue #17, and by erickok from ticket #10)
   *
   * @param XMLRPC server URI
   */
  public XMLRPCClient(URI uri) {
    SchemeRegistry registry = new SchemeRegistry();
    registry.register(new Scheme("http", new PlainSocketFactory(), 80));
    registry.register(new Scheme("https", SSLSocketFactory.getSocketFactory(), 443));

    postMethod = new HttpPost(uri);
    postMethod.addHeader("Content-Type", "text/xml");

    // WARNING
    // I had to disable "Expect: 100-Continue" header since I had
    // two second delay between sending http POST request and POST body
    httpParams = postMethod.getParams();
    HttpProtocolParams.setUseExpectContinue(httpParams, false);
    this.client =
        new DefaultHttpClient(new ThreadSafeClientConnManager(httpParams, registry), httpParams);
  }
  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;
  }
Example #26
0
 private YammerHttpClient() {
   SchemeRegistry schemeRegistry = new SchemeRegistry();
   schemeRegistry.register(
       new Scheme(HttpHost.DEFAULT_SCHEME_NAME, 80, PlainSocketFactory.getSocketFactory()));
   schemeRegistry.register(new Scheme("https", 443, SSLSocketFactory.getSocketFactory()));
   DefaultHttpClient defaultHttpClient =
       new DefaultHttpClient(new ThreadSafeClientConnManager(schemeRegistry));
   HttpParams params = defaultHttpClient.getParams();
   HttpConnectionParams.setSoTimeout(params, 5000);
   HttpConnectionParams.setConnectionTimeout(params, 5000);
   HttpConnectionParams.setTcpNoDelay(params, true);
   HttpProtocolParams.setContentCharset(params, HTTP.UTF_8);
   HttpProtocolParams.setHttpElementCharset(params, HTTP.UTF_8);
   HttpProtocolParams.setVersion(params, HttpVersion.HTTP_1_1);
   HttpClientParams.setRedirecting(params, false);
   httpClient = defaultHttpClient;
 }
Example #27
0
 /** Construct a downloader for a certain repository as a certain user. */
 public Downloader(String host, int port, String context, String user, String pass)
     throws IOException {
   m_fedoraUrlStart =
       Administrator.getProtocol() + "://" + host + ":" + port + "/" + context + "/" + "get/";
   m_authScope = new AuthScope(host, AuthScope.ANY_PORT, AuthScope.ANY_REALM);
   m_creds = new UsernamePasswordCredentials(user, pass);
   if (Administrator.getProtocol().equalsIgnoreCase("https")) {
     m_cManager
         .getSchemeRegistry()
         .register(new Scheme("https", port, SSLSocketFactory.getSocketFactory()));
   } else {
     m_cManager
         .getSchemeRegistry()
         .register(
             new Scheme(Administrator.getProtocol(), port, PlainSocketFactory.getSocketFactory()));
   }
 }
Example #28
0
  private HttpUtils() {
    SchemeRegistry reg = new SchemeRegistry();
    // sslSocFactory.setHostnameVerifier(SSLSocketFactory.BROWSER_COMPATIBLE_HOSTNAME_VERIFIER);
    reg.register(new Scheme("https", SSLSocketFactory.getSocketFactory(), 443));
    reg.register(new Scheme("http", PlainSocketFactory.getSocketFactory(), 80));

    params_ = new BasicHttpParams();
    HttpConnectionParams.setConnectionTimeout(params_, 5000);
    HttpConnectionParams.setSoTimeout(params_, 3000);
    params_.setParameter(ConnManagerPNames.MAX_TOTAL_CONNECTIONS, 30);
    params_.setParameter(ConnManagerPNames.MAX_CONNECTIONS_PER_ROUTE, new ConnPerRouteBean(30));
    params_.setParameter(HttpProtocolParams.USE_EXPECT_CONTINUE, false);
    // HttpProtocolParams.setVersion(params_, HttpVersion.HTTP_1_1);

    ThreadSafeClientConnManager connMgr = new ThreadSafeClientConnManager(params_, reg);
    client_ = new DefaultHttpClient(connMgr, params_);
    // context_ = new BasicHttpContext();
  }
  /**
   * Create a new instance of the HttpComponentsHttpInvokerRequestExecutor with a default {@link
   * HttpClient} that uses a default {@code
   * org.apache.http.impl.conn.PoolingClientConnectionManager}.
   */
  public HttpComponentsHttpInvokerRequestExecutor() {
    org.apache.http.conn.scheme.SchemeRegistry schemeRegistry =
        new org.apache.http.conn.scheme.SchemeRegistry();
    schemeRegistry.register(
        new org.apache.http.conn.scheme.Scheme(
            "http", 80, org.apache.http.conn.scheme.PlainSocketFactory.getSocketFactory()));
    schemeRegistry.register(
        new org.apache.http.conn.scheme.Scheme(
            "https", 443, org.apache.http.conn.ssl.SSLSocketFactory.getSocketFactory()));

    org.apache.http.impl.conn.PoolingClientConnectionManager connectionManager =
        new org.apache.http.impl.conn.PoolingClientConnectionManager(schemeRegistry);
    connectionManager.setMaxTotal(DEFAULT_MAX_TOTAL_CONNECTIONS);
    connectionManager.setDefaultMaxPerRoute(DEFAULT_MAX_CONNECTIONS_PER_ROUTE);

    this.httpClient = new org.apache.http.impl.client.DefaultHttpClient(connectionManager);
    setReadTimeout(DEFAULT_READ_TIMEOUT_MILLISECONDS);
  }
Example #30
0
  /**
   * Create a thread-safe client. This client does not do redirecting, to allow us to capture
   * correct "error" codes.
   *
   * @return HttpClient
   */
  public static final DefaultHttpClient createHttpClient(Context mContext) {
    // Sets up the http part of the service.
    final SchemeRegistry supportedSchemes = new SchemeRegistry();

    // Register the "http" protocol scheme, it is required
    // by the default operator to look up socket factories.
    final SocketFactory sf = PlainSocketFactory.getSocketFactory();
    supportedSchemes.register(new Scheme("http", sf, 80));
    supportedSchemes.register(new Scheme("https", SSLSocketFactory.getSocketFactory(), 443));

    // Set some client http client parameter defaults.
    final HttpParams httpParams = createHttpParams(mContext);
    HttpClientParams.setRedirecting(httpParams, false);

    final ClientConnectionManager ccm =
        new ThreadSafeClientConnManager(httpParams, supportedSchemes);
    return new DefaultHttpClient(ccm, httpParams);
  }