List of usage examples for org.apache.http.conn.routing HttpRoute HttpRoute
public HttpRoute(final HttpHost target, final InetAddress local, final boolean secure)
From source file:httpclient.conn.ManagerConnectDirect.java
/** * Main entry point to this example.// ww w .java 2 s . com * * @param args ignored */ public final static void main(String[] args) throws Exception { final HttpHost target = new HttpHost("jakarta.apache.org", 80, "http"); setup(); // some general setup ClientConnectionManager clcm = createManager(); HttpRequest req = createRequest(target); HttpContext ctx = createContext(); System.out.println("preparing route to " + target); HttpRoute route = new HttpRoute(target, null, supportedSchemes.getScheme(target).isLayered()); System.out.println("requesting connection for " + route); ClientConnectionRequest connRequest = clcm.requestConnection(route, null); ManagedClientConnection conn = connRequest.getConnection(0, null); try { System.out.println("opening connection"); conn.open(route, ctx, getParams()); System.out.println("sending request"); conn.sendRequestHeader(req); // there is no request entity conn.flush(); System.out.println("receiving response header"); HttpResponse rsp = conn.receiveResponseHeader(); System.out.println("----------------------------------------"); System.out.println(rsp.getStatusLine()); Header[] headers = rsp.getAllHeaders(); for (int i = 0; i < headers.length; i++) { System.out.println(headers[i]); } System.out.println("----------------------------------------"); System.out.println("closing connection"); conn.close(); } finally { if (conn.isOpen()) { System.out.println("shutting down connection"); try { conn.shutdown(); } catch (Exception x) { System.out.println("problem during shutdown"); x.printStackTrace(System.out); } } System.out.println("releasing connection"); clcm.releaseConnection(conn, -1, null); } }
From source file:org.eclipse.thym.core.internal.util.HttpUtil.java
/** * Set the proxy settings from ProxyService. * This method sets a {@link HttpRoutePlanner} to the client * //from w w w . jav a 2 s .co m * @param client */ public static void setupProxy(final DefaultHttpClient client) { client.setRoutePlanner(new HttpRoutePlanner() { @Override public HttpRoute determineRoute(HttpHost target, HttpRequest request, HttpContext context) throws HttpException { //use forced route if one exists HttpRoute route = ConnRouteParams.getForcedRoute(request.getParams()); if (route != null) return route; // if layered, is it secure? final Scheme scheme = client.getConnectionManager().getSchemeRegistry().getScheme(target); final boolean secure = scheme.isLayered(); HttpHost host = null; try { IProxyData[] proxyDatas = getEclipseProxyData(new URI(target.toURI())); for (IProxyData data : proxyDatas) { if (data.getType().equals(IProxyData.HTTP_PROXY_TYPE)) { host = new HttpHost(data.getHost(), data.getPort()); break; } } } catch (URISyntaxException e) { HybridCore.log(IStatus.ERROR, "Incorrect URI", e); } if (host == null) { return new HttpRoute(target, null, secure); } return new HttpRoute(target, null, host, secure); } }); }
From source file:org.jboss.tools.feedhenry.ui.model.HttpUtil.java
/** * Set the proxy settings from ProxyService. * This method sets a {@link HttpRoutePlanner} to the client * //from w w w . ja v a 2s . c om * @param client */ static void setupProxy(final DefaultHttpClient client) { client.setRoutePlanner(new HttpRoutePlanner() { /* (non-Javadoc) * @see org.apache.http.conn.routing.HttpRoutePlanner#determineRoute(org.apache.http.HttpHost, org.apache.http.HttpRequest, org.apache.http.protocol.HttpContext) */ @Override public HttpRoute determineRoute(HttpHost target, HttpRequest request, HttpContext context) throws HttpException { //use forced route if one exists HttpRoute route = ConnRouteParams.getForcedRoute(request.getParams()); if (route != null) return route; // if layered, is it secure? final Scheme scheme = client.getConnectionManager().getSchemeRegistry().getScheme(target); final boolean secure = scheme.isLayered(); final IProxyService proxy = FHPlugin.getDefault().getProxyService(); HttpHost host = null; if (proxy != null) { try { IProxyData[] proxyDatas = proxy.select(new URI(target.toURI())); for (IProxyData data : proxyDatas) { if (data.getType().equals(IProxyData.HTTP_PROXY_TYPE)) { host = new HttpHost(data.getHost(), data.getPort()); break; } } } catch (URISyntaxException e) { FHPlugin.log(IStatus.ERROR, "Incorrect URI", e); } } if (host == null) { return new HttpRoute(target, null, secure); } return new HttpRoute(target, null, host, secure); } }); }
From source file:com.seajas.search.contender.http.ExclusiveConnectionManager.java
/** * Set the exclusions.//from w w w. java 2s .c om * * @param exclusions */ public void setRouteExclusions(final String exclusions) { for (String exclusion : StringUtils.tokenizeToStringArray(exclusions, ",", true, true)) { setMaxPerRoute(new HttpRoute(new HttpHost(exclusion), null, false), getMaxTotal()); setMaxPerRoute(new HttpRoute(new HttpHost(exclusion), null, true), getMaxTotal()); } }
From source file:com.wudaosoft.net.httpclient.Request.java
protected void init() throws KeyManagementException, NoSuchAlgorithmException, KeyStoreException, CertificateException, IOException { Args.notNull(hostConfig, "Host config"); SSLConnectionSocketFactory sslConnectionSocketFactory = null; if (sslcontext == null) { if (hostConfig.getCA() != null) { // Trust root CA and all self-signed certs SSLContext sslcontext1 = SSLContexts.custom().loadTrustMaterial(hostConfig.getCA(), hostConfig.getCAPassword(), TrustSelfSignedStrategy.INSTANCE).build(); // Allow TLSv1 protocol only sslConnectionSocketFactory = new SSLConnectionSocketFactory(sslcontext1, new String[] { "TLSv1" }, null, SSLConnectionSocketFactory.getDefaultHostnameVerifier()); } else {//from w ww.j a va2 s. c o m if (isTrustAll) { SSLContext sslcontext1 = SSLContext.getInstance("TLS"); TrustManager[] trustAllCerts = new TrustManager[] { new X509TrustManager() { public X509Certificate[] getAcceptedIssuers() { return null; } @Override public void checkClientTrusted(java.security.cert.X509Certificate[] arg0, String arg1) throws CertificateException { } @Override public void checkServerTrusted(java.security.cert.X509Certificate[] arg0, String arg1) throws CertificateException { } } }; sslcontext1.init(null, trustAllCerts, null); sslConnectionSocketFactory = new SSLConnectionSocketFactory(sslcontext1, NoopHostnameVerifier.INSTANCE); } else { sslConnectionSocketFactory = SSLConnectionSocketFactory.getSocketFactory(); } } } else { sslConnectionSocketFactory = new SSLConnectionSocketFactory(sslcontext, new String[] { "TLSv1" }, null, SSLConnectionSocketFactory.getDefaultHostnameVerifier()); } if (keepAliveStrategy == null) { keepAliveStrategy = new ConnectionKeepAliveStrategy() { public long getKeepAliveDuration(HttpResponse response, HttpContext context) { // Honor 'keep-alive' header HeaderElementIterator it = new BasicHeaderElementIterator( response.headerIterator(HTTP.CONN_KEEP_ALIVE)); while (it.hasNext()) { HeaderElement he = it.nextElement(); String param = he.getName(); String value = he.getValue(); if (value != null && param.equalsIgnoreCase("timeout")) { try { return Long.parseLong(value) * 1000; } catch (NumberFormatException ignore) { } } } // HttpHost target = (HttpHost) // context.getAttribute(HttpClientContext.HTTP_TARGET_HOST); // if // ("xxxxx".equalsIgnoreCase(target.getHostName())) // { // // Keep alive for 5 seconds only // return 3 * 1000; // } else { // // otherwise keep alive for 30 seconds // return 30 * 1000; // } return 30 * 1000; } }; } if (retryHandler == null) { retryHandler = new HttpRequestRetryHandler() { public boolean retryRequest(IOException exception, int executionCount, HttpContext context) { if (executionCount >= 3) { // Do not retry if over max retry count return false; } if (exception instanceof InterruptedIOException) { // Timeout return false; } if (exception instanceof UnknownHostException) { // Unknown host return false; } if (exception instanceof ConnectTimeoutException) { // Connection refused return false; } if (exception instanceof SSLException) { // SSL handshake exception return false; } HttpClientContext clientContext = HttpClientContext.adapt(context); HttpRequest request = clientContext.getRequest(); boolean idempotent = !(request instanceof HttpEntityEnclosingRequest); if (idempotent) { // Retry if the request is considered idempotent return true; } return false; } }; } connManager = new PoolingHttpClientConnectionManager(RegistryBuilder.<ConnectionSocketFactory>create() .register("http", PlainConnectionSocketFactory.getSocketFactory()) .register("https", sslConnectionSocketFactory).build()); if (hostConfig.getHost() != null) { connManager.setMaxTotal(hostConfig.getPoolSize() + 60); connManager.setMaxPerRoute( new HttpRoute(hostConfig.getHost(), null, !HttpHost.DEFAULT_SCHEME_NAME.equals(hostConfig.getHost().getSchemeName())), hostConfig.getPoolSize()); connManager.setDefaultMaxPerRoute(20); } else { connManager.setMaxTotal(hostConfig.getPoolSize()); int hostCount = hostConfig.getHostCount() == 0 ? 10 : hostConfig.getHostCount(); connManager.setDefaultMaxPerRoute(hostConfig.getPoolSize() / hostCount); } // connManager.setValidateAfterInactivity(2000); // Create socket configuration SocketConfig socketConfig = SocketConfig.custom().setTcpNoDelay(true).setSoKeepAlive(isKeepAlive).build(); connManager.setDefaultSocketConfig(socketConfig); // Create connection configuration ConnectionConfig connectionConfig = ConnectionConfig.custom() .setMalformedInputAction(CodingErrorAction.IGNORE) .setUnmappableInputAction(CodingErrorAction.IGNORE) .setCharset(hostConfig.getCharset() == null ? Consts.UTF_8 : hostConfig.getCharset()).build(); connManager.setDefaultConnectionConfig(connectionConfig); new IdleConnectionMonitorThread(connManager).start(); if (requestInterceptor == null) { requestInterceptor = new SortHeadersInterceptor(hostConfig); } if (!hostConfig.isMulticlient()) { defaultHttpContext = HttpClientContext.create(); httpClient = create(); } }
From source file:org.apache.http.impl.conn.TestPoolingHttpClientConnectionManager.java
@Test public void testTargetConnect() throws Exception { final HttpHost target = new HttpHost("somehost", -1, "https"); final InetAddress remote = InetAddress.getByAddress(new byte[] { 10, 0, 0, 1 }); final InetAddress local = InetAddress.getByAddress(new byte[] { 127, 0, 0, 1 }); final HttpRoute route = new HttpRoute(target, local, true); final CPoolEntry entry = new CPoolEntry(LogFactory.getLog(getClass()), "id", route, conn, -1, TimeUnit.MILLISECONDS); entry.markRouteComplete();/*from w w w. j av a2s. c om*/ Mockito.when(future.isCancelled()).thenReturn(Boolean.FALSE); Mockito.when(conn.isOpen()).thenReturn(true); Mockito.when(future.isCancelled()).thenReturn(false); Mockito.when(future.get(1, TimeUnit.SECONDS)).thenReturn(entry); Mockito.when(pool.lease(route, null, null)).thenReturn(future); final ConnectionRequest connRequest1 = mgr.requestConnection(route, null); final HttpClientConnection conn1 = connRequest1.get(1, TimeUnit.SECONDS); Assert.assertNotNull(conn1); final HttpClientContext context = HttpClientContext.create(); final SocketConfig sconfig = SocketConfig.custom().build(); mgr.setDefaultSocketConfig(sconfig); Mockito.when(dnsResolver.resolve("somehost")).thenReturn(new InetAddress[] { remote }); Mockito.when(schemePortResolver.resolve(target)).thenReturn(8443); Mockito.when(socketFactoryRegistry.lookup("https")).thenReturn(plainSocketFactory); Mockito.when(plainSocketFactory.createSocket(Mockito.<HttpContext>any())).thenReturn(socket); Mockito.when(plainSocketFactory.connectSocket(Mockito.anyInt(), Mockito.eq(socket), Mockito.<HttpHost>any(), Mockito.<InetSocketAddress>any(), Mockito.<InetSocketAddress>any(), Mockito.<HttpContext>any())) .thenReturn(socket); mgr.connect(conn1, route, 123, context); Mockito.verify(dnsResolver, Mockito.times(1)).resolve("somehost"); Mockito.verify(schemePortResolver, Mockito.times(1)).resolve(target); Mockito.verify(plainSocketFactory, Mockito.times(1)).createSocket(context); Mockito.verify(plainSocketFactory, Mockito.times(1)).connectSocket(123, socket, target, new InetSocketAddress(remote, 8443), new InetSocketAddress(local, 0), context); mgr.routeComplete(conn1, route, context); }
From source file:org.apache.http.impl.nio.conn.TestPoolingHttpClientAsyncConnectionManager.java
@Test public void testConnectionInitializeHttps() throws Exception { final HttpHost target = new HttpHost("somehost", 443, "https"); final HttpRoute route = new HttpRoute(target, null, true); final HttpContext context = new BasicHttpContext(); final Log log = Mockito.mock(Log.class); final CPoolEntry poolentry = new CPoolEntry(log, "some-id", route, conn, -1, TimeUnit.MILLISECONDS); poolentry.markRouteComplete();//www. j a v a 2 s . com final NHttpClientConnection managedConn = CPoolProxy.newProxy(poolentry); Mockito.when(conn.getIOSession()).thenReturn(iosession); Mockito.when(sslStrategy.upgrade(target, iosession)).thenReturn(iosession); connman.startRoute(managedConn, route, context); Mockito.verify(sslStrategy).upgrade(target, iosession); Mockito.verify(conn).bind(iosession); }
From source file:org.apache.http.impl.nio.conn.TestPoolingHttpClientAsyncConnectionManager.java
@Test(expected = UnsupportedSchemeException.class) public void testConnectionInitializeUnknownScheme() throws Exception { final HttpHost target = new HttpHost("somehost", -1, "whatever"); final HttpRoute route = new HttpRoute(target, null, true); final HttpContext context = new BasicHttpContext(); final Log log = Mockito.mock(Log.class); final CPoolEntry poolentry = new CPoolEntry(log, "some-id", route, conn, -1, TimeUnit.MILLISECONDS); poolentry.markRouteComplete();//from w w w . j av a 2 s. c om final NHttpClientConnection managedConn = CPoolProxy.newProxy(poolentry); Mockito.when(conn.getIOSession()).thenReturn(iosession); Mockito.when(sslStrategy.upgrade(target, iosession)).thenReturn(iosession); connman.startRoute(managedConn, route, context); }
From source file:org.apache.http.impl.nio.conn.TestPoolingHttpClientAsyncConnectionManager.java
@Test public void testResolveLocalAddress() throws Exception { final InternalAddressResolver addressResolver = new InternalAddressResolver(schemePortResolver, dnsResolver);/*from w ww . j av a2s .co m*/ final HttpHost target = new HttpHost("localhost"); final byte[] ip = new byte[] { 10, 0, 0, 10 }; final HttpRoute route = new HttpRoute(target, InetAddress.getByAddress(ip), false); final InetSocketAddress address = (InetSocketAddress) addressResolver.resolveLocalAddress(route); Assert.assertNotNull(address); Assert.assertEquals(InetAddress.getByAddress(ip), address.getAddress()); Assert.assertEquals(0, address.getPort()); }