/** 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); }
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; }
/** * 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()); }
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; } }
/** * 获取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; }
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; }
/** * Releases the resources held by the given HTTP client.<br> * Note that no further connections can be made upon a disposed HTTP client. * * @param client the HTTP client to be disposed. */ public static void disposeHttpClient(HttpClient client) { if (client != null) { ClientConnectionManager manager = client.getConnectionManager(); manager.shutdown(); client = null; } }
private HttpClient createHttpClient() { DefaultHttpClient client = new DefaultHttpClient(); ClientConnectionManager mgr = client.getConnectionManager(); HttpParams params = client.getParams(); return new DefaultHttpClient( new ThreadSafeClientConnManager(params, mgr.getSchemeRegistry()), params); }
private void shutdownHttpClient() { if (mHttpClient != null) { ClientConnectionManager manager = mHttpClient.getConnectionManager(); if (manager != null) { manager.shutdown(); } mHttpClient = null; } }
public void close() { if (closed) return; if (createdHttpClient && httpClient != null) { ClientConnectionManager manager = httpClient.getConnectionManager(); if (manager != null) { manager.shutdown(); } } closed = true; }
/** * 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()); }
/** * 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; }
/** * This method is invoked when the thread is started. It invokes the base class implementation. */ @Override public void run() { super.run(); // obtain connection if (connection == null) return; // problem obtaining connection try { request_spec.context.setAttribute(ExecutionContext.HTTP_CONNECTION, connection); doOpenConnection(); HttpRequest request = (HttpRequest) request_spec.context.getAttribute(ExecutionContext.HTTP_REQUEST); request_spec.executor.preProcess(request, request_spec.processor, request_spec.context); response = request_spec.executor.execute(request, connection, request_spec.context); request_spec.executor.postProcess(response, request_spec.processor, request_spec.context); doConsumeResponse(); } catch (Exception ex) { if (exception != null) exception = ex; } finally { conn_manager.releaseConnection(connection, -1, null); } }
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; }
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; } }
public void release() { if (executor != null) { executor.shutdown(); } if (connManager != null) { connManager.shutdown(); } client = null; }
private static boolean uploader(HttpClient httpClient, HttpPost httpPost) { HttpResponse httpResponse; ResponseHandler<String> res = new BasicResponseHandler(); boolean result = false; try { httpResponse = httpClient.execute(httpPost); result = (httpResponse.getStatusLine().getStatusCode() == HttpStatus.SC_OK); if (result) { String response = res.handleResponse(httpResponse).toString(); result = response.contains("upload success"); } } catch (Exception e) { } finally { if (httpClient != null) { ClientConnectionManager ccm = httpClient.getConnectionManager(); if (ccm != null) ccm.shutdown(); } } return result; }
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; } }
/** * 创建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); } }
/** 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); }
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); }
private static void shutdown(InternalAPI api) { ClientConnectionManager connectionManager = (ClientConnectionManager) Whitebox.getInternalState(api, "connectionManager"); connectionManager.shutdown(); }
// non-javadoc, see interface ClientRequestDirector public HttpResponse execute(HttpHost target, HttpRequest request, HttpContext context) throws HttpException, IOException { HttpRequest orig = request; RequestWrapper origWrapper = wrapRequest(orig); origWrapper.setParams(params); HttpRoute origRoute = determineRoute(target, origWrapper, context); RoutedRequest roureq = new RoutedRequest(origWrapper, origRoute); long timeout = ConnManagerParams.getTimeout(params); int execCount = 0; boolean reuse = false; HttpResponse response = null; boolean done = false; try { while (!done) { // In this loop, the RoutedRequest may be replaced by a // followup request and route. The request and route passed // in the method arguments will be replaced. The original // request is still available in 'orig'. RequestWrapper wrapper = roureq.getRequest(); HttpRoute route = roureq.getRoute(); // See if we have a user token bound to the execution context Object userToken = context.getAttribute(ClientContext.USER_TOKEN); // Allocate connection if needed if (managedConn == null) { ClientConnectionRequest connRequest = connManager.requestConnection(route, userToken); if (orig instanceof AbortableHttpRequest) { ((AbortableHttpRequest) orig).setConnectionRequest(connRequest); } try { managedConn = connRequest.getConnection(timeout, TimeUnit.MILLISECONDS); } catch (InterruptedException interrupted) { InterruptedIOException iox = new InterruptedIOException(); iox.initCause(interrupted); throw iox; } if (HttpConnectionParams.isStaleCheckingEnabled(params)) { // validate connection this.log.debug("Stale connection check"); if (managedConn.isStale()) { this.log.debug("Stale connection detected"); // BEGIN android-changed try { managedConn.close(); } catch (IOException ignored) { // SSLSocket's will throw IOException // because they can't send a "close // notify" protocol message to the // server. Just supresss any // exceptions related to closing the // stale connection. } // END android-changed } } } if (orig instanceof AbortableHttpRequest) { ((AbortableHttpRequest) orig).setReleaseTrigger(managedConn); } // Reopen connection if needed if (!managedConn.isOpen()) { managedConn.open(route, context, params); } // BEGIN android-added else { // b/3241899 set the per request timeout parameter on reused connections managedConn.setSocketTimeout(HttpConnectionParams.getSoTimeout(params)); } // END android-added try { establishRoute(route, context); } catch (TunnelRefusedException ex) { if (this.log.isDebugEnabled()) { this.log.debug(ex.getMessage()); } response = ex.getResponse(); break; } // Reset headers on the request wrapper wrapper.resetHeaders(); // Re-write request URI if needed rewriteRequestURI(wrapper, route); // Use virtual host if set target = (HttpHost) wrapper.getParams().getParameter(ClientPNames.VIRTUAL_HOST); if (target == null) { target = route.getTargetHost(); } HttpHost proxy = route.getProxyHost(); // Populate the execution context context.setAttribute(ExecutionContext.HTTP_TARGET_HOST, target); context.setAttribute(ExecutionContext.HTTP_PROXY_HOST, proxy); context.setAttribute(ExecutionContext.HTTP_CONNECTION, managedConn); context.setAttribute(ClientContext.TARGET_AUTH_STATE, targetAuthState); context.setAttribute(ClientContext.PROXY_AUTH_STATE, proxyAuthState); // Run request protocol interceptors requestExec.preProcess(wrapper, httpProcessor, context); context.setAttribute(ExecutionContext.HTTP_REQUEST, wrapper); boolean retrying = true; while (retrying) { // Increment total exec count (with redirects) execCount++; // Increment exec count for this particular request wrapper.incrementExecCount(); if (wrapper.getExecCount() > 1 && !wrapper.isRepeatable()) { throw new NonRepeatableRequestException( "Cannot retry request " + "with a non-repeatable request entity"); } try { if (this.log.isDebugEnabled()) { this.log.debug("Attempt " + execCount + " to execute request"); } response = requestExec.execute(wrapper, managedConn, context); retrying = false; } catch (IOException ex) { this.log.debug("Closing the connection."); managedConn.close(); if (retryHandler.retryRequest(ex, execCount, context)) { if (this.log.isInfoEnabled()) { this.log.info( "I/O exception (" + ex.getClass().getName() + ") caught when processing request: " + ex.getMessage()); } if (this.log.isDebugEnabled()) { this.log.debug(ex.getMessage(), ex); } this.log.info("Retrying request"); } else { throw ex; } // If we have a direct route to the target host // just re-open connection and re-try the request if (route.getHopCount() == 1) { this.log.debug("Reopening the direct connection."); managedConn.open(route, context, params); } else { // otherwise give up throw ex; } } } // Run response protocol interceptors response.setParams(params); requestExec.postProcess(response, httpProcessor, context); // The connection is in or can be brought to a re-usable state. reuse = reuseStrategy.keepAlive(response, context); if (reuse) { // Set the idle duration of this connection long duration = keepAliveStrategy.getKeepAliveDuration(response, context); managedConn.setIdleDuration(duration, TimeUnit.MILLISECONDS); } RoutedRequest followup = handleResponse(roureq, response, context); if (followup == null) { done = true; } else { if (reuse) { this.log.debug("Connection kept alive"); // Make sure the response body is fully consumed, if present HttpEntity entity = response.getEntity(); if (entity != null) { entity.consumeContent(); } // entity consumed above is not an auto-release entity, // need to mark the connection re-usable explicitly managedConn.markReusable(); } else { managedConn.close(); } // check if we can use the same connection for the followup if (!followup.getRoute().equals(roureq.getRoute())) { releaseConnection(); } roureq = followup; } userToken = this.userTokenHandler.getUserToken(context); context.setAttribute(ClientContext.USER_TOKEN, userToken); if (managedConn != null) { managedConn.setState(userToken); } } // while not done // check for entity, release connection if possible if ((response == null) || (response.getEntity() == null) || !response.getEntity().isStreaming()) { // connection not needed and (assumed to be) in re-usable state if (reuse) managedConn.markReusable(); releaseConnection(); } else { // install an auto-release entity HttpEntity entity = response.getEntity(); entity = new BasicManagedEntity(entity, managedConn, reuse); response.setEntity(entity); } return response; } catch (HttpException ex) { abortConnection(); throw ex; } catch (IOException ex) { abortConnection(); throw ex; } catch (RuntimeException ex) { abortConnection(); throw ex; } } // execute