コード例 #1
0
  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;
    }
  }
コード例 #2
0
 /**
  * 获取SSL验证的HttpClient
  *
  * @param httpClient
  * @return
  */
 public static HttpClient getSSLInstance(HttpClient httpClient) {
   ClientConnectionManager ccm = httpClient.getConnectionManager();
   SchemeRegistry sr = ccm.getSchemeRegistry();
   sr.register(new Scheme("https", MySSLSocketFactory.getInstance(), 443));
   httpClient = new DefaultHttpClient(ccm, httpClient.getParams());
   return httpClient;
 }
コード例 #3
0
ファイル: OSI.java プロジェクト: ash2005/Sec2
  /** httpGet */
  public static String httpGet(final String exist, String database, String android_id)
      throws IOException, HttpHostConnectException, ConnectException {
    String getUrl = "http://" + exist + ":50001/exist/rest/db/calendar/" + android_id + ".xml";
    LogHelper.logV(c, "httpGet: " + getUrl);

    DefaultHttpClient httpClient = new DefaultHttpClient();
    ClientConnectionManager ccm = httpClient.getConnectionManager();
    HttpParams params = httpClient.getParams();

    httpClient =
        new DefaultHttpClient(
            new ThreadSafeClientConnManager(params, ccm.getSchemeRegistry()), 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);
  }
コード例 #4
0
  /**
   * Wrap a basic HttpClient object in an all trusting SSL enabled HttpClient object.
   *
   * @param base The HttpClient to wrap.
   * @return The SSL wrapped HttpClient.
   * @throws GeneralSecurityException
   * @throws IOException
   */
  private HttpClient trustAllSslEnable(HttpClient base) throws GeneralSecurityException {
    // Get an initialized SSL context
    // Create a trust manager that does not validate certificate chains
    TrustManager[] trustAllCerts =
        new TrustManager[] {
          new X509TrustManager() {
            @Override
            public java.security.cert.X509Certificate[] getAcceptedIssuers() {
              return null;
            }

            @Override
            public void checkClientTrusted(
                java.security.cert.X509Certificate[] certs, String authType) {}

            @Override
            public void checkServerTrusted(
                java.security.cert.X509Certificate[] certs, String authType) {}
          }
        };

    // set up the all-trusting trust manager
    SSLContext sc = SSLContext.getInstance("SSL"); // $NON-NLS-1$
    sc.init(null, trustAllCerts, new java.security.SecureRandom());

    SSLSocketFactory sf = new SSLSocketFactory(sc, SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);
    ClientConnectionManager ccm = base.getConnectionManager();
    SchemeRegistry sr = ccm.getSchemeRegistry();
    Scheme https = new Scheme("https", 443, sf); // $NON-NLS-1$
    sr.register(https);
    return new DefaultHttpClient(ccm, base.getParams());
  }
コード例 #5
0
  public HttpClient getMockHttpClient() {
    HttpClient mock = Mockito.mock(HttpClient.class);
    HttpParams paramsMock = Mockito.mock(HttpParams.class);
    ClientConnectionManager connectionMock = Mockito.mock(ClientConnectionManager.class);
    HttpResponse hrMocked = Mockito.mock(HttpResponse.class);
    StatusLine slMocked = Mockito.mock(StatusLine.class);

    Header headerMocked = Mockito.mock(Header.class);

    Mockito.when(connectionMock.getSchemeRegistry())
        .thenReturn(SchemeRegistryFactory.createDefault());
    Mockito.when(hrMocked.getEntity()).thenReturn(heMocked);
    Mockito.when(mock.getParams()).thenReturn(paramsMock);
    Mockito.when(mock.getConnectionManager()).thenReturn(connectionMock);
    try {
      Mockito.when(mock.execute(Mockito.any(HttpUriRequest.class), Mockito.any(HttpContext.class)))
          .thenReturn(hrMocked);
    } catch (ClientProtocolException e) {
      // TODO Auto-generated catch block
      e.printStackTrace();
    } catch (IOException e) {
      // TODO Auto-generated catch block
      e.printStackTrace();
    }
    Mockito.when(hrMocked.getStatusLine()).thenReturn(slMocked);
    Mockito.when(slMocked.getStatusCode()).thenReturn(200);
    Mockito.when(heMocked.getContentType()).thenReturn(headerMocked);
    Mockito.when(headerMocked.getElements()).thenReturn(new HeaderElement[0]);
    return mock;
  }
コード例 #6
0
  /**
   * Creates the CONNECT request for tunnelling. Called by {@link #createTunnelToTarget
   * createTunnelToTarget}.
   *
   * @param route the route to establish
   * @param context the context for request execution
   * @return the CONNECT request for tunnelling
   */
  protected HttpRequest createConnectRequest(HttpRoute route, HttpContext context) {
    // see RFC 2817, section 5.2 and
    // INTERNET-DRAFT: Tunneling TCP based protocols through
    // Web proxy servers

    HttpHost target = route.getTargetHost();

    String host = target.getHostName();
    int port = target.getPort();
    if (port < 0) {
      Scheme scheme = connManager.getSchemeRegistry().getScheme(target.getSchemeName());
      port = scheme.getDefaultPort();
    }

    StringBuilder buffer = new StringBuilder(host.length() + 6);
    buffer.append(host);
    buffer.append(':');
    buffer.append(Integer.toString(port));

    String authority = buffer.toString();
    ProtocolVersion ver = HttpProtocolParams.getVersion(params);
    HttpRequest req = new BasicHttpRequest("CONNECT", authority, ver);

    return req;
  }
コード例 #7
0
    public static synchronized DefaultHttpClient getThreadSafeClient() {

      if (clientThreadSafe != null) return clientThreadSafe;

      clientThreadSafe = new DefaultHttpClient();

      ClientConnectionManager mgr = clientThreadSafe.getConnectionManager();

      HttpParams params = clientThreadSafe.getParams();

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

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

      return clientThreadSafe;
    }
コード例 #8
0
ファイル: ConvoidApp.java プロジェクト: Pewpewarrows/Convoid
  private HttpClient createHttpClient() {
    DefaultHttpClient client = new DefaultHttpClient();
    ClientConnectionManager mgr = client.getConnectionManager();
    HttpParams params = client.getParams();

    return new DefaultHttpClient(
        new ThreadSafeClientConnManager(params, mgr.getSchemeRegistry()), params);
  }
コード例 #9
0
  /**
   * Wrap a basic HttpClient object in a Fedora SSL enabled HttpClient (which includes Fedora SSL
   * authentication cert) object.
   *
   * @param base The HttpClient to wrap.
   * @return The SSL wrapped HttpClient.
   * @throws GeneralSecurityException
   * @throws IOException
   */
  private HttpClient fedoraSslEnable(HttpClient base)
      throws GeneralSecurityException, FileNotFoundException, IOException {

    // Get a SSL related instance for setting up SSL connections.
    FedoraSSL fedoraSSL = FedoraSSLFactory.getInstance();
    SSLSocketFactory sf =
        new SSLSocketFactory(
            fedoraSSL.getInitializedSSLContext(), // may throw FileNotFoundE
            SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);
    ClientConnectionManager ccm = base.getConnectionManager();
    SchemeRegistry sr = ccm.getSchemeRegistry();
    Scheme https = new Scheme("https", 443, sf); // $NON-NLS-1$
    sr.register(https);
    return new DefaultHttpClient(ccm, base.getParams());
  }
コード例 #10
0
ファイル: MyUtil.java プロジェクト: gaotong2055/spider_mvn
  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 java.security.cert.X509Certificate[] getAcceptedIssuers() {
              return null;
            }

            @Override
            public void checkClientTrusted(
                java.security.cert.X509Certificate[] chain, String authType)
                throws java.security.cert.CertificateException {
              // TODO Auto-generated method stub

            }

            @Override
            public void checkServerTrusted(
                java.security.cert.X509Certificate[] chain, String authType)
                throws java.security.cert.CertificateException {
              // TODO Auto-generated method stub

            }
          };
      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) {
      ex.printStackTrace();
      return null;
    }
  }
コード例 #11
0
  public static HttpClient wrapClient(HttpClient base) {
    try {
      SSLContext ctx = SSLContext.getInstance("sslv3");
      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;
            }
          };
      X509HostnameVerifier verifier =
          new X509HostnameVerifier() {

            public void verify(String arg0, SSLSocket arg1) throws IOException {}

            public void verify(String arg0, X509Certificate arg1) throws SSLException {}

            public void verify(String arg0, String[] arg1, String[] arg2) throws SSLException {}

            public boolean verify(String hostname, SSLSession session) {
              return true;
            }
          };
      ctx.init(null, new TrustManager[] {tm}, null);
      SSLSocketFactory ssf = new SSLSocketFactory(ctx, verifier);
      ClientConnectionManager ccm = base.getConnectionManager();
      SchemeRegistry sr = ccm.getSchemeRegistry();
      sr.register(new Scheme("https", 443, ssf));
      return new DefaultHttpClient(ccm, base.getParams());
    } catch (Exception ex) {
      ex.printStackTrace();
      return null;
    }
  }
コード例 #12
0
  private void updateAuthState(
      final AuthState authState, final HttpHost host, final CredentialsProvider credsProvider) {

    if (!authState.isValid()) {
      return;
    }

    String hostname = host.getHostName();
    int port = host.getPort();
    if (port < 0) {
      Scheme scheme = connManager.getSchemeRegistry().getScheme(host);
      port = scheme.getDefaultPort();
    }

    AuthScheme authScheme = authState.getAuthScheme();
    AuthScope authScope =
        new AuthScope(hostname, port, authScheme.getRealm(), authScheme.getSchemeName());

    if (this.log.isDebugEnabled()) {
      this.log.debug("Authentication scope: " + authScope);
    }
    Credentials creds = authState.getCredentials();
    if (creds == null) {
      creds = credsProvider.getCredentials(authScope);
      if (this.log.isDebugEnabled()) {
        if (creds != null) {
          this.log.debug("Found credentials");
        } else {
          this.log.debug("Credentials not found");
        }
      }
    } else {
      if (authScheme.isComplete()) {
        this.log.debug("Authentication failed");
        creds = null;
      }
    }
    authState.setAuthScope(authScope);
    authState.setCredentials(creds);
  }
コード例 #13
0
 /**
  * 创建HttpClient对象
  *
  * @return
  */
 public static HttpClient buildHttpClient() {
   try {
     SSLContext sslcontext = SSLContext.getInstance("TLS");
     sslcontext.init(null, new TrustManager[] {tm}, null);
     SSLSocketFactory ssf = new SSLSocketFactory(sslcontext);
     ClientConnectionManager ccm = new DefaultHttpClient().getConnectionManager();
     SchemeRegistry sr = ccm.getSchemeRegistry();
     sr.register(new Scheme("https", 443, ssf));
     HttpParams params = new BasicHttpParams();
     params.setParameter(CoreConnectionPNames.CONNECTION_TIMEOUT, 8000);
     params.setParameter(CoreConnectionPNames.SO_TIMEOUT, 8000);
     HttpClient httpclient = new DefaultHttpClient(ccm, params);
     httpclient
         .getParams()
         .setParameter(
             HTTP.USER_AGENT,
             "Mozilla/5.0 (compatible; MSIE 9.0; Windows NT 6.1; Trident/5.0; BOIE9;ZHCN)");
     return httpclient;
   } catch (Exception e) {
     throw new IllegalStateException(e);
   }
 }
コード例 #14
0
ファイル: OSI.java プロジェクト: ash2005/Sec2
  /** httpPost */
  public static String httpPost(final String url) throws IOException {

    LogHelper.logV(c, "httpPost: " + url);

    DefaultHttpClient httpClient = new DefaultHttpClient();
    ClientConnectionManager ccm = httpClient.getConnectionManager();
    HttpParams params = httpClient.getParams();

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

    HttpPost post = new HttpPost(url);

    post.setHeader("Location", "localhost:50082");
    post.setHeader("Connection", "close");
    post.setHeader("Content-Type", "text/xml");

    HttpResponse response = httpClient.execute(post);

    HttpEntity httpEntity = response.getEntity();
    return EntityUtils.toString(httpEntity);
  }
コード例 #15
0
 public HttpClient getThreadSafeClient()
 {
   ClientConnectionManager localClientConnectionManager = this.client.getConnectionManager();
   HttpParams localHttpParams = this.client.getParams();
   this.client = new DefaultHttpClient(new ThreadSafeClientConnManager(localHttpParams, localClientConnectionManager.getSchemeRegistry()), localHttpParams);
   return this.client;
 }