private SSLSocketFactory newSslSocketFactory() {
      try {
        // Get an instance of the Bouncy Castle KeyStore format
        KeyStore trusted = KeyStore.getInstance("BKS");
        // Get the raw resource, which contains the keystore with
        // your trusted certificates (root and any intermediate certs)
        InputStream in =
            context.getResources().openRawResource(tracker.springversion1.R.raw.mykeystore);

        try {
          // Initialize the keystore with the provided trusted
          // certificates
          // Also provide the password of the keystore
          trusted.load(in, "mysecret".toCharArray());
        } finally {
          in.close();
        }
        // Pass the keystore to the SSLSocketFactory. The factory is
        // responsible
        // for the verification of the server certificate.
        SSLSocketFactory sf = new SSLSocketFactory(trusted);
        // Hostname verification from certificate
        // http://hc.apache.org/httpcomponents-client-ga/tutorial/html/connmgmt.html#d4e506
        sf.setHostnameVerifier(SSLSocketFactory.STRICT_HOSTNAME_VERIFIER);
        //				 ALLOW_ALL_HOSTNAME_VERIFIER
        return sf;
      } catch (Exception e) {
        throw new AssertionError(e);
      }
    }
  static {
    try {
      String configPath = System.getProperty("configPath");
      File configFile = new File(configPath);
      InputStream stream = new FileInputStream(configFile);
      configProperties = new Properties();
      configProperties.load(stream);

      if (Boolean.valueOf(configProperties.getProperty("acceptCertificate"))) {
        log.debug("accepting certificates");
        KeyStore trustStore = KeyStore.getInstance(KeyStore.getDefaultType());
        trustStore.load(null, null);

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

        clCore
            .getUmssoHttpClient()
            .getConnectionManager()
            .getSchemeRegistry()
            .register(new Scheme("http", PlainSocketFactory.getSocketFactory(), 80));
        clCore
            .getUmssoHttpClient()
            .getConnectionManager()
            .getSchemeRegistry()
            .register(new Scheme("https", sf, 443));
      }

    } catch (Exception e) {
      log.error("Can not initialize DAR monitor " + e.getMessage());
    }
  }
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);
    }
  }
  @SuppressWarnings({"deprecation"})
  private static SSLSocketFactory createSSLSocketFactory() {
    try {
      SSLContext ctx = SSLContext.getInstance("TLS");
      X509TrustManager tm =
          new X509TrustManager() {
            @Override
            public void checkClientTrusted(X509Certificate[] xcs, String string)
                throws CertificateException {}

            @Override
            public void checkServerTrusted(X509Certificate[] xcs, String string)
                throws CertificateException {}

            public X509Certificate[] getAcceptedIssuers() {
              return null;
            }
          };
      ctx.init(null, new X509TrustManager[] {tm}, null);
      String[] enabled = {"SSL_RSA_WITH_NULL_MD5", "SSL_RSA_WITH_NULL_SHA"};
      ctx.createSSLEngine().setEnabledCipherSuites(enabled);

      SSLSocketFactory ssf = new SSLSocketFactory(ctx);
      ssf.setHostnameVerifier(SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);

      return ssf;
    } catch (Exception ex) {
      ex.printStackTrace();
      return null;
    }
  }
    /**
     * 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 static HttpClient wrapClient(HttpClient base) {
    try {
      SSLContext ctx = SSLContext.getInstance("TLS");
      X509TrustManager tm =
          new X509TrustManager() {
            public void checkClientTrusted(X509Certificate[] xcs, String string)
                throws CertificateException {}

            public void checkServerTrusted(X509Certificate[] xcs, String string)
                throws CertificateException {}

            public X509Certificate[] getAcceptedIssuers() {
              return null;
            }
          };
      ctx.init(null, new TrustManager[] {tm}, null);
      SSLSocketFactory ssf = new SSLSocketFactory(ctx);
      ssf.setHostnameVerifier(SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);
      ClientConnectionManager ccm = base.getConnectionManager();
      SchemeRegistry sr = ccm.getSchemeRegistry();
      sr.register(new Scheme("https", ssf, 443));
      return new DefaultHttpClient(ccm, base.getParams());
    } catch (Exception ex) {
      return null;
    }
  }
Exemple #7
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();
   }
 }
  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 #9
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();
  }
  public static HttpClient getCertifiedHttpClient() throws IDPTokenManagerException {
    HttpClient client = null;
    InputStream inStream = null;
    try {
      if (Constants.SERVER_PROTOCOL.equalsIgnoreCase("https://")) {
        KeyStore localTrustStore = KeyStore.getInstance("BKS");
        inStream =
            IdentityProxy.getInstance()
                .getContext()
                .getResources()
                .openRawResource(R.raw.emm_truststore);
        localTrustStore.load(inStream, Constants.TRUSTSTORE_PASSWORD.toCharArray());

        SchemeRegistry schemeRegistry = new SchemeRegistry();
        schemeRegistry.register(
            new Scheme("http", PlainSocketFactory.getSocketFactory(), Constants.HTTP));
        SSLSocketFactory sslSocketFactory = new SSLSocketFactory(localTrustStore);
        sslSocketFactory.setHostnameVerifier(SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);
        schemeRegistry.register(new Scheme("https", sslSocketFactory, Constants.HTTPS));
        HttpParams params = new BasicHttpParams();
        ClientConnectionManager connectionManager =
            new ThreadSafeClientConnManager(params, schemeRegistry);

        client = new DefaultHttpClient(connectionManager, params);

      } else {
        client = new DefaultHttpClient();
      }

    } catch (KeyStoreException e) {
      String errorMsg = "Error occurred while accessing keystore.";
      Log.e(TAG, errorMsg);
      throw new IDPTokenManagerException(errorMsg, e);
    } catch (CertificateException e) {
      String errorMsg = "Error occurred while loading certificate.";
      Log.e(TAG, errorMsg);
      throw new IDPTokenManagerException(errorMsg, e);
    } catch (NoSuchAlgorithmException e) {
      String errorMsg = "Error occurred while due to mismatch of defined algorithm.";
      Log.e(TAG, errorMsg);
      throw new IDPTokenManagerException(errorMsg, e);
    } catch (UnrecoverableKeyException e) {
      String errorMsg = "Error occurred while accessing keystore.";
      Log.e(TAG, errorMsg);
      throw new IDPTokenManagerException(errorMsg, e);
    } catch (KeyManagementException e) {
      String errorMsg = "Error occurred while accessing keystore.";
      Log.e(TAG, errorMsg);
      throw new IDPTokenManagerException(errorMsg, e);
    } catch (IOException e) {
      String errorMsg = "Error occurred while loading trust store. ";
      Log.e(TAG, errorMsg);
      throw new IDPTokenManagerException(errorMsg, e);
    } finally {
      StreamHandlerUtil.closeInputStream(inStream, TAG);
    }
    return client;
  }
 private static SocketFactory createSocketFactory(boolean allowInvalidCerts) {
   SocketFactory sslSocketFactory;
   if (allowInvalidCerts) {
     sslSocketFactory = new WeaveSSLSocketFactory();
   } else {
     sslSocketFactory = SSLSocketFactory.getSocketFactory();
     ((SSLSocketFactory) sslSocketFactory).setHostnameVerifier(new WeaveHostnameVerifier());
   }
   return sslSocketFactory;
 }
 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);
 }
Exemple #13
0
  /**
   * detector url
   *
   * @param url
   * @param jksPath
   * @return
   */
  public static boolean detectUrl(String url, String jksPath, String jksPassword) {
    // logger.debug(">>>detectUrl(" + url + ", " + jksPath + ", " + jksPassword + ")");

    boolean result = false;

    HttpClient httpclient = new DefaultHttpClient();
    try {
      if (null != jksPath && !"".equals(jksPath) && null != jksPassword) {
        KeyStore trustStore = KeyStore.getInstance(KeyStore.getDefaultType());
        FileInputStream instream = null;
        try {
          instream = new FileInputStream(new File(jksPath));
          trustStore.load(instream, jksPassword.toCharArray());
        } finally {
          if (instream != null) {
            instream.close();
          }
        }

        SSLSocketFactory socketFactory = new SSLSocketFactory(trustStore);
        socketFactory.setHostnameVerifier(
            SSLSocketFactory
                .ALLOW_ALL_HOSTNAME_VERIFIER); // otherwise url's hostname must be 'ratestserver'
        Scheme sch = new Scheme("https", socketFactory, 443);

        httpclient.getConnectionManager().getSchemeRegistry().register(sch);
      }

      httpclient.getParams().setParameter(CoreConnectionPNames.CONNECTION_TIMEOUT, 3 * 1000);
      HttpGet httpget = new HttpGet(url);
      HttpResponse response = httpclient.execute(httpget);

      /*
      // make sure to use a proxy that supports CONNECT
      HttpHost proxy = new HttpHost("127.0.0.1", 8080, "http");
      httpclient.getParams().setParameter(ConnRoutePNames.DEFAULT_PROXY, proxy);
      */

      logger.debug("response.getStatusLine()=" + response.getStatusLine());
      if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
        result = true;
      }
    } catch (SSLPeerUnverifiedException e) {
      result = true;
      logger.error(null, e);
    } catch (Exception e) {
      logger.error(null, e);
    } finally {
      httpclient.getConnectionManager().shutdown();
    }

    // logger.debug("<<<detectUrl(" + url + ", " + jksPath + ", " + jksPassword + ") - return
    // value=" + result);
    return result;
  }
 /**
  * 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;
 }
Exemple #15
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);
  }
 private static HttpClient createUnsecureClient(HttpParams params) {
   try {
     KeyStore trustStore = KeyStore.getInstance(KeyStore.getDefaultType());
     trustStore.load(null, null);
     SSLSocketFactory ssf = new AndroidSSLSocketFactory(trustStore);
     ssf.setHostnameVerifier(SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);
     SchemeRegistry sr = new SchemeRegistry();
     sr.register(new Scheme("http", PlainSocketFactory.getSocketFactory(), 80));
     sr.register(new Scheme("https", ssf, 443));
     ClientConnectionManager ccm = new SingleClientConnManager(params, sr);
     return new DefaultHttpClient(ccm, params);
   } catch (Exception ex) {
     ex.printStackTrace();
     return null;
   }
 }
  /**
   * 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);
  }
  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;
  }
  private static SSLSocketFactory getSSLSocketFactory() {
    try {
      KeyStore trustStore = KeyStore.getInstance(KeyStore.getDefaultType());

      trustStore.load(null, null);

      SSLSocketFactory sslSocketFactory = new TrustAllSSLSocketFactory(trustStore);
      sslSocketFactory.setHostnameVerifier(SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);

      return sslSocketFactory;
    } catch (Exception e) {
      e.printStackTrace();
    }

    return null;
  }
  /**
   * 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);
    }
  }
  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;
  }
  /**
   * 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;
  }
  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;
  }
Exemple #25
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;
  }
  public static HttpClient getNewHttpClient() {
    try {
      KeyStore trustStore = KeyStore.getInstance(KeyStore.getDefaultType());
      trustStore.load(null, null);
      SSLSocketFactory sf = new CustomSSLSocketFactory(trustStore);
      sf.setHostnameVerifier(SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);
      HttpParams params = new BasicHttpParams();
      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();
    }
  }
 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;
 }
Exemple #29
0
  public boolean initialize() {

    try {
      initParams = new RemoteWrapperParamParser(getActiveAddressBean(), true);
      uid = Math.random();

      postParameters = new ArrayList<NameValuePair>();
      postParameters.add(
          new BasicNameValuePair(PushDelivery.NOTIFICATION_ID_KEY, Double.toString(uid)));
      postParameters.add(
          new BasicNameValuePair(
              PushDelivery.LOCAL_CONTACT_POINT, initParams.getLocalContactPoint()));
      // Init the http client
      if (initParams.isSSLRequired()) {
        KeyStore trustStore = KeyStore.getInstance(KeyStore.getDefaultType());
        trustStore.load(
            new FileInputStream(new File("conf/servertestkeystore")),
            Main.getContainerConfig().getSSLKeyStorePassword().toCharArray());
        SSLSocketFactory socketFactory = new SSLSocketFactory(trustStore);
        socketFactory.setHostnameVerifier(SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);
        int sslPort =
            Main.getContainerConfig().getSSLPort() > 0
                ? Main.getContainerConfig().getSSLPort()
                : ContainerConfig.DEFAULT_SSL_PORT;
        Scheme sch = new Scheme("https", socketFactory, sslPort);
        httpclient.getConnectionManager().getSchemeRegistry().register(sch);
      }
      Scheme plainsch =
          new Scheme(
              "http",
              PlainSocketFactory.getSocketFactory(),
              Main.getContainerConfig().getContainerPort());
      httpclient.getConnectionManager().getSchemeRegistry().register(plainsch);
      //
      lastReceivedTimestamp = initParams.getStartTime();
      structure = registerAndGetStructure();
    } catch (Exception e) {
      logger.error(e.getMessage(), e);
      NotificationRegistry.getInstance().removeNotification(uid);
      return false;
    }

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