List of usage examples for org.apache.http.impl.client HttpClientBuilder addInterceptorLast
public final HttpClientBuilder addInterceptorLast(final HttpRequestInterceptor itcp)
From source file:org.archive.modules.recrawl.wbm.WbmPersistLoadProcessor.java
public synchronized HttpClient getHttpClient() { if (client == null) { if (conman == null) { conman = new PoolingHttpClientConnectionManager(); conman.setDefaultMaxPerRoute(maxConnections); conman.setMaxTotal(Math.max(conman.getMaxTotal(), maxConnections)); }// www. ja va 2 s . c o m HttpClientBuilder builder = HttpClientBuilder.create().disableCookieManagement() .setConnectionManager(conman); builder.useSystemProperties(); // TODO: use setDefaultHeaders for adding requestHeaders? It's a bit painful // because we need to convert it to a Collection of Header objects. // config code for older version of httpclient. // builder.setDefaultSocketConfig(SocketConfig.custom().setSoTimeout(socketTimeout).build()); // HttpParams params = client.getParams(); // params.setIntParameter(CoreConnectionPNames.SO_TIMEOUT, socketTimeout); // params.setIntParameter(CoreConnectionPNames.CONNECTION_TIMEOUT, connectionTimeout); // setup request/response intercepter for handling gzip-compressed response. // Disabled because httpclient 4.3.3 sends "Accept-Encoding: gzip,deflate" by // default. Response parsing will fail If gzip-decompression ResponseInterceptor // is installed. builder.addInterceptorLast(new HttpRequestInterceptor() { @Override public void process(final HttpRequest request, final HttpContext context) { // System.err.println("RequestInterceptor"); // if (request.containsHeader("Accept-Encoding")) { // System.err.println("already has Accept-Encoding: " + request.getHeaders("Accept-Encoding")[0]); // } // if (gzipAccepted) { // if (!request.containsHeader("Accept-Encoding")) { // request.addHeader("Accept-Encoding", "gzip"); // } // } // add extra headers configured. if (requestHeaders != null) { for (Entry<String, String> ent : requestHeaders.entrySet()) { request.addHeader(ent.getKey(), ent.getValue()); } } } }); // builder.addInterceptorFirst(new HttpResponseInterceptor() { // @Override // public void process(final HttpResponse response, final HttpContext context) // throws HttpException, IOException { // HttpEntity entity = response.getEntity(); // Header ceheader = entity.getContentEncoding(); // if (ceheader != null && contains(ceheader.getElements(), "gzip")) { // response.setEntity(new GzipInflatingHttpEntityWrapper(response.getEntity())); // } // } // }); this.client = builder.build(); } return client; }
From source file:net.www_eee.portal.channels.ProxyChannel.java
/** * Construct and configure the {@link HttpClient} to be used to * {@linkplain #doProxyRequest(Page.Request, Channel.Mode) proxy} content while fulfilling the specified * <code>pageRequest</code>. This method will also configure {@linkplain ProxyRequestInterceptor request} and * {@linkplain ProxyResponseInterceptor response} interceptors on the created client. * /*www . ja v a 2s .com*/ * @param pageRequest The {@link net.www_eee.portal.Page.Request Request} currently being processed. * @return The created {@link HttpClient}. * @throws WWWEEEPortal.Exception If a problem occurred while determining the result. * @see #doProxyRequest(Page.Request, Channel.Mode) * @see #PROXY_CLIENT_HOOK * @see ProxyRequestInterceptor * @see ProxyResponseInterceptor */ protected CloseableHttpClient createProxyClient(final Page.Request pageRequest) throws WWWEEEPortal.Exception { final org.apache.http.client.CookieStore proxyClientCookieStore = createProxyClientCookieStore(pageRequest); Object[] context = new Object[] { proxyClientManager, proxyClientCookieStore }; HttpClientBuilder proxyClientBuilder = PROXY_CLIENT_HOOK.value(plugins, context, pageRequest); if (proxyClientBuilder == null) { final HttpClientBuilder pcb = HttpClientBuilder.create(); Optional.ofNullable(proxyClientManager) .ifPresent((proxyClientManager) -> pcb.setConnectionManager(proxyClientManager)); proxyClientBuilder = pcb; proxyClientBuilder.setDefaultCookieStore(proxyClientCookieStore); proxyClientBuilder = proxyClientBuilder.addInterceptorLast(new ProxyRequestInterceptor(pageRequest)); proxyClientBuilder = proxyClientBuilder.addInterceptorLast(new ProxyResponseInterceptor(pageRequest)); } proxyClientBuilder = PROXY_CLIENT_HOOK .requireFilteredResult(PROXY_CLIENT_HOOK.filter(plugins, context, pageRequest, proxyClientBuilder)); return proxyClientBuilder.build(); }
From source file:org.apache.hive.jdbc.HiveConnection.java
private CloseableHttpClient getHttpClient(Boolean useSsl) throws SQLException { boolean isCookieEnabled = sessConfMap.get(JdbcConnectionParams.COOKIE_AUTH) == null || (!JdbcConnectionParams.COOKIE_AUTH_FALSE .equalsIgnoreCase(sessConfMap.get(JdbcConnectionParams.COOKIE_AUTH))); String cookieName = sessConfMap.get(JdbcConnectionParams.COOKIE_NAME) == null ? JdbcConnectionParams.DEFAULT_COOKIE_NAMES_HS2 : sessConfMap.get(JdbcConnectionParams.COOKIE_NAME); CookieStore cookieStore = isCookieEnabled ? new BasicCookieStore() : null; HttpClientBuilder httpClientBuilder; // Request interceptor for any request pre-processing logic HttpRequestInterceptor requestInterceptor; Map<String, String> additionalHttpHeaders = new HashMap<String, String>(); // Retrieve the additional HttpHeaders for (Map.Entry<String, String> entry : sessConfMap.entrySet()) { String key = entry.getKey(); if (key.startsWith(JdbcConnectionParams.HTTP_HEADER_PREFIX)) { additionalHttpHeaders.put(key.substring(JdbcConnectionParams.HTTP_HEADER_PREFIX.length()), entry.getValue());/* w w w. jav a2 s. c om*/ } } // Configure http client for kerberos/password based authentication if (isKerberosAuthMode()) { /** * Add an interceptor which sets the appropriate header in the request. * It does the kerberos authentication and get the final service ticket, * for sending to the server before every request. * In https mode, the entire information is encrypted */ requestInterceptor = new HttpKerberosRequestInterceptor( sessConfMap.get(JdbcConnectionParams.AUTH_PRINCIPAL), host, getServerHttpUrl(useSsl), assumeSubject, cookieStore, cookieName, useSsl, additionalHttpHeaders); } else { // Check for delegation token, if present add it in the header String tokenStr = getClientDelegationToken(sessConfMap); if (tokenStr != null) { requestInterceptor = new HttpTokenAuthInterceptor(tokenStr, cookieStore, cookieName, useSsl, additionalHttpHeaders); } else { /** * Add an interceptor to pass username/password in the header. * In https mode, the entire information is encrypted */ requestInterceptor = new HttpBasicAuthInterceptor(getUserName(), getPassword(), cookieStore, cookieName, useSsl, additionalHttpHeaders); } } // Configure http client for cookie based authentication if (isCookieEnabled) { // Create a http client with a retry mechanism when the server returns a status code of 401. httpClientBuilder = HttpClients.custom() .setServiceUnavailableRetryStrategy(new ServiceUnavailableRetryStrategy() { @Override public boolean retryRequest(final HttpResponse response, final int executionCount, final HttpContext context) { int statusCode = response.getStatusLine().getStatusCode(); boolean ret = statusCode == 401 && executionCount <= 1; // Set the context attribute to true which will be interpreted by the request // interceptor if (ret) { context.setAttribute(Utils.HIVE_SERVER2_RETRY_KEY, Utils.HIVE_SERVER2_RETRY_TRUE); } return ret; } @Override public long getRetryInterval() { // Immediate retry return 0; } }); } else { httpClientBuilder = HttpClientBuilder.create(); } // In case the server's idletimeout is set to a lower value, it might close it's side of // connection. However we retry one more time on NoHttpResponseException httpClientBuilder.setRetryHandler(new HttpRequestRetryHandler() { @Override public boolean retryRequest(IOException exception, int executionCount, HttpContext context) { if (executionCount > 1) { LOG.info("Retry attempts to connect to server exceeded."); return false; } if (exception instanceof org.apache.http.NoHttpResponseException) { LOG.info("Could not connect to the server. Retrying one more time."); return true; } return false; } }); // Add the request interceptor to the client builder httpClientBuilder.addInterceptorFirst(requestInterceptor); // Add an interceptor to add in an XSRF header httpClientBuilder.addInterceptorLast(new XsrfHttpRequestInterceptor()); // Configure http client for SSL if (useSsl) { String useTwoWaySSL = sessConfMap.get(JdbcConnectionParams.USE_TWO_WAY_SSL); String sslTrustStorePath = sessConfMap.get(JdbcConnectionParams.SSL_TRUST_STORE); String sslTrustStorePassword = sessConfMap.get(JdbcConnectionParams.SSL_TRUST_STORE_PASSWORD); KeyStore sslTrustStore; SSLConnectionSocketFactory socketFactory; SSLContext sslContext; /** * The code within the try block throws: SSLInitializationException, KeyStoreException, * IOException, NoSuchAlgorithmException, CertificateException, KeyManagementException & * UnrecoverableKeyException. We don't want the client to retry on any of these, * hence we catch all and throw a SQLException. */ try { if (useTwoWaySSL != null && useTwoWaySSL.equalsIgnoreCase(JdbcConnectionParams.TRUE)) { socketFactory = getTwoWaySSLSocketFactory(); } else if (sslTrustStorePath == null || sslTrustStorePath.isEmpty()) { // Create a default socket factory based on standard JSSE trust material socketFactory = SSLConnectionSocketFactory.getSocketFactory(); } else { // Pick trust store config from the given path sslTrustStore = KeyStore.getInstance(JdbcConnectionParams.SSL_TRUST_STORE_TYPE); try (FileInputStream fis = new FileInputStream(sslTrustStorePath)) { sslTrustStore.load(fis, sslTrustStorePassword.toCharArray()); } sslContext = SSLContexts.custom().loadTrustMaterial(sslTrustStore, null).build(); socketFactory = new SSLConnectionSocketFactory(sslContext, new DefaultHostnameVerifier(null)); } final Registry<ConnectionSocketFactory> registry = RegistryBuilder.<ConnectionSocketFactory>create() .register("https", socketFactory).build(); httpClientBuilder.setConnectionManager(new BasicHttpClientConnectionManager(registry)); } catch (Exception e) { String msg = "Could not create an https connection to " + jdbcUriString + ". " + e.getMessage(); throw new SQLException(msg, " 08S01", e); } } return httpClientBuilder.build(); }
From source file:org.opennms.core.web.HttpClientWrapper.java
public CloseableHttpClient getClient() { if (m_httpClient == null) { final HttpClientBuilder httpClientBuilder = HttpClientBuilder.create(); final RequestConfig.Builder requestConfigBuilder = RequestConfig.custom(); if (!m_reuseConnections) { httpClientBuilder.setConnectionReuseStrategy(new NoConnectionReuseStrategy()); }/* w w w . j a va 2 s. co m*/ if (m_usePreemptiveAuth) { enablePreemptiveAuth(httpClientBuilder); } if (m_useSystemProxySettings) { httpClientBuilder.setRoutePlanner(new SystemDefaultRoutePlanner(ProxySelector.getDefault())); } if (!isEmpty(m_cookieSpec)) { requestConfigBuilder.setCookieSpec(m_cookieSpec); } if (m_cookieStore != null) { httpClientBuilder.setDefaultCookieStore(m_cookieStore); } if (m_username != null) { setCredentials(httpClientBuilder, m_username, m_password); } if (m_socketTimeout != null) { requestConfigBuilder.setSocketTimeout(m_socketTimeout); } if (m_connectionTimeout != null) { requestConfigBuilder.setConnectTimeout(m_connectionTimeout); } if (m_retries != null) { httpClientBuilder.setRetryHandler(new HttpRequestRetryOnExceptionHandler(m_retries, false)); } if (m_sslContext.size() != 0) { configureSSLContext(httpClientBuilder); } for (final HttpRequestInterceptor interceptor : m_requestInterceptors) { httpClientBuilder.addInterceptorLast(interceptor); } for (final HttpResponseInterceptor interceptor : m_responseInterceptors) { httpClientBuilder.addInterceptorLast(interceptor); } if (m_useLaxRedirect) { httpClientBuilder.setRedirectStrategy(new LaxRedirectStrategy()); } httpClientBuilder.setDefaultRequestConfig(requestConfigBuilder.build()); m_httpClient = httpClientBuilder.build(); } return m_httpClient; }