List of usage examples for org.apache.http.impl.client HttpClientBuilder addInterceptorFirst
public final HttpClientBuilder addInterceptorFirst(final HttpRequestInterceptor itcp)
From source file:org.apache.solr.client.solrj.impl.HttpClientUtil.java
private static HttpClientBuilder setupBuilder(HttpClientBuilder builder, SolrParams config) { Builder requestConfigBuilder = RequestConfig.custom() .setRedirectsEnabled(config.getBool(HttpClientUtil.PROP_FOLLOW_REDIRECTS, false)) .setDecompressionEnabled(false) .setConnectTimeout(config.getInt(HttpClientUtil.PROP_CONNECTION_TIMEOUT, DEFAULT_CONNECT_TIMEOUT)) .setSocketTimeout(config.getInt(HttpClientUtil.PROP_SO_TIMEOUT, DEFAULT_SO_TIMEOUT)); String cpolicy = cookiePolicy; if (cpolicy != null) { requestConfigBuilder.setCookieSpec(cpolicy); }//from ww w.j a v a 2 s .co m RequestConfig requestConfig = requestConfigBuilder.build(); HttpClientBuilder retBuilder = builder.setDefaultRequestConfig(requestConfig); if (config.getBool(HttpClientUtil.PROP_USE_RETRY, true)) { retBuilder = retBuilder.setRetryHandler(new SolrHttpRequestRetryHandler(3)); } else { retBuilder = retBuilder.setRetryHandler(NO_RETRY); } final String basicAuthUser = config.get(HttpClientUtil.PROP_BASIC_AUTH_USER); final String basicAuthPass = config.get(HttpClientUtil.PROP_BASIC_AUTH_PASS); if (basicAuthUser != null && basicAuthPass != null) { CredentialsProvider credsProvider = new BasicCredentialsProvider(); credsProvider.setCredentials(AuthScope.ANY, new UsernamePasswordCredentials(basicAuthUser, basicAuthPass)); retBuilder.setDefaultCredentialsProvider(credsProvider); } if (config.getBool(HttpClientUtil.PROP_ALLOW_COMPRESSION, false)) { retBuilder.addInterceptorFirst(new UseCompressionRequestInterceptor()); retBuilder.addInterceptorFirst(new UseCompressionResponseInterceptor()); } else { retBuilder.disableContentCompression(); } return retBuilder; }
From source file:com.github.sardine.FunctionalSardineTest.java
@Test public void testGetRange() throws Exception { final HttpClientBuilder client = HttpClientBuilder.create(); client.addInterceptorFirst(new HttpResponseInterceptor() { public void process(final HttpResponse r, final HttpContext context) throws HttpException, IOException { // Verify partial content response assertEquals(206, r.getStatusLine().getStatusCode()); assertNotNull(r.getHeaders(HttpHeaders.CONTENT_RANGE)); assertEquals(1, r.getHeaders(HttpHeaders.CONTENT_RANGE).length); }/* w w w . jav a 2 s . co m*/ }); Sardine sardine = new SardineImpl(client); // mod_dav supports Range headers for GET final String url = "http://sudo.ch/dav/anon/sardine/single/file"; // Resume final Map<String, String> header = Collections.singletonMap(HttpHeaders.RANGE, "bytes=" + 1 + "-"); final InputStream in = sardine.get(url, header); assertNotNull(in); }
From source file:com.github.sardine.FunctionalSardineTest.java
@Test public void testGetSingleFileGzip() throws Exception { final HttpClientBuilder client = HttpClientBuilder.create(); client.addInterceptorFirst(new HttpResponseInterceptor() { public void process(final HttpResponse r, final HttpContext context) throws HttpException, IOException { assertEquals(200, r.getStatusLine().getStatusCode()); assertNotNull(r.getHeaders(HttpHeaders.CONTENT_ENCODING)); assertEquals(1, r.getHeaders(HttpHeaders.CONTENT_ENCODING).length); assertEquals("gzip", r.getHeaders(HttpHeaders.CONTENT_ENCODING)[0].getValue()); }//from w w w . j a v a 2 s. c o m }); Sardine sardine = new SardineImpl(client); sardine.enableCompression(); // final String url = "http://sardine.googlecode.com/svn/trunk/README.html"; final String url = "http://sudo.ch/dav/anon/sardine/single/file"; final InputStream in = sardine.get(url); assertNotNull(in); assertNotNull(in.read()); try { in.close(); } catch (EOFException e) { fail("Issue https://issues.apache.org/jira/browse/HTTPCLIENT-1075 pending"); } }
From source file:com.github.sardine.FunctionalSardineTest.java
@Test public void testPutRange() throws Exception { final HttpClientBuilder client = HttpClientBuilder.create(); client.addInterceptorFirst(new HttpResponseInterceptor() { public void process(final HttpResponse r, final HttpContext context) throws HttpException, IOException { assertEquals(201, r.getStatusLine().getStatusCode()); }//from w ww.jav a 2 s . c o m }); Sardine sardine = new SardineImpl(client); // mod_dav supports Range headers for PUT final String url = "http://sudo.ch/dav/anon/sardine/" + UUID.randomUUID().toString(); sardine.put(url, new ByteArrayInputStream("Te".getBytes("UTF-8"))); try { // Append to existing file final Map<String, String> header = Collections.singletonMap(HttpHeaders.CONTENT_RANGE, "bytes " + 2 + "-" + 3 + "/" + 4); client.addInterceptorFirst(new HttpRequestInterceptor() { public void process(final HttpRequest r, final HttpContext context) throws HttpException, IOException { assertNotNull(r.getHeaders(HttpHeaders.CONTENT_RANGE)); assertEquals(1, r.getHeaders(HttpHeaders.CONTENT_RANGE).length); } }); client.addInterceptorFirst(new HttpResponseInterceptor() { public void process(final HttpResponse r, final HttpContext context) throws HttpException, IOException { assertEquals(204, r.getStatusLine().getStatusCode()); } }); sardine.put(url, new ByteArrayInputStream("st".getBytes("UTF-8")), header); assertEquals("Test", new BufferedReader(new InputStreamReader(sardine.get(url), "UTF-8")).readLine()); } finally { sardine.delete(url); } }
From source file:de.shadowhunt.subversion.internal.AbstractHelper.java
public HttpClient getHttpClient(final String username, final HttpRequestInterceptor... interceptors) { final HttpClientBuilder builder = HttpClientBuilder.create(); final CredentialsProvider cp = new BasicCredentialsProvider(); final Credentials credentials = new UsernamePasswordCredentials(username, PASSWORD); cp.setCredentials(AuthScope.ANY, credentials); builder.setDefaultCredentialsProvider(cp); for (HttpRequestInterceptor interceptor : interceptors) { builder.addInterceptorFirst(interceptor); }/* w w w . j a v a 2 s. c o m*/ builder.setRetryHandler(new SubversionRequestRetryHandler()); return builder.build(); }
From source file:uk.org.openeyes.oink.itest.adapters.ITFacadeToProxy.java
@Test public void testCanGetMetadataOfOpenEyes() { String facadeUri = (String) facadeProps.get("facade.uri"); // Create a context and get the client factory so it can be configured FhirContext ctx = new FhirContext(); IRestfulClientFactory clientFactory = ctx.getRestfulClientFactory(); // Create an HTTP Client Builder HttpClientBuilder builder = HttpClientBuilder.create(); // This interceptor adds HTTP username/password to every request String username = (String) proxyProps.get("proxy.username"); String password = (String) proxyProps.get("proxy.password"); builder.addInterceptorFirst(new HttpBasicAuthInterceptor(username, password)); builder.addInterceptorFirst(new HttpRequestInterceptor() { @Override/*from w ww . j a v a2s . c o m*/ public void process(HttpRequest req, HttpContext context) throws HttpException, IOException { req.addHeader("Accept", "application/json+fhir; charset=UTF-8"); } }); // Use the new HTTP client builder clientFactory.setHttpClient(builder.build()); IGenericClient client = clientFactory.newGenericClient(facadeUri); Conformance c = client.conformance(); assertNotNull(c); }
From source file:uk.org.openeyes.oink.itest.adapters.ITFacadeToProxy.java
@Test public void testGetPatients() { String facadeUri = (String) facadeProps.get("facade.uri"); // Create a context and get the client factory so it can be configured FhirContext ctx = new FhirContext(); IRestfulClientFactory clientFactory = ctx.getRestfulClientFactory(); // Create an HTTP Client Builder HttpClientBuilder builder = HttpClientBuilder.create(); // This interceptor adds HTTP username/password to every request String username = (String) proxyProps.get("proxy.username"); String password = (String) proxyProps.get("proxy.password"); builder.addInterceptorFirst(new HttpBasicAuthInterceptor(username, password)); builder.addInterceptorFirst(new HttpRequestInterceptor() { @Override/*from w w w .j a v a2 s. c o m*/ public void process(HttpRequest req, HttpContext context) throws HttpException, IOException { req.addHeader("Accept", "application/json+fhir; charset=UTF-8"); } }); // Use the new HTTP client builder clientFactory.setHttpClient(builder.build()); IGenericClient client = clientFactory.newGenericClient(facadeUri); Bundle response = client.search().forResource(Patient.class).execute(); assertNotNull(response); assertNotEquals(0, response.getEntries().size()); }
From source file:com.neiljbrown.brighttalk.channels.reportingapi.client.spring.AppConfig.java
/** * @return The instance of {@link HttpClient} to be used by {@link ClientHttpRequestFactory} to create client * requests. Pre-configured to support basic authentication using externally configured API user credentials, and to * utilise the API service's support for HTTP response compression (using gzip). *//*w w w.ja v a 2 s . co m*/ @Bean public HttpClient httpClient() { HttpClientBuilder builder = HttpClients.custom(); // Configure the basic authentication credentials to use for all requests CredentialsProvider credentialsProvider = new BasicCredentialsProvider(); AuthScope authScope = new AuthScope(this.apiServiceHostName, this.apiServicePort); UsernamePasswordCredentials credentials = new UsernamePasswordCredentials(this.apiUserKey, this.apiUserSecret); credentialsProvider.setCredentials(authScope, credentials); builder.setDefaultCredentialsProvider(credentialsProvider); builder.addInterceptorFirst(new PreemptiveBasicAuthHttpRequestInterceptor()); // Configure default request headers List<Header> headers = new ArrayList<>(5); headers.add(new BasicHeader("Api-Client", SpringApiClientImpl.class.getCanonicalName())); if (this.defaultRequestHeaders != null) { for (String header : this.defaultRequestHeaders) { String[] headerNameAndValue = header.split("==", 2); if (headerNameAndValue.length == 2) { headers.add(new BasicHeader(headerNameAndValue[0], headerNameAndValue[1])); } } } builder.setDefaultHeaders(headers); // HttpClient should by default set the Accept-Encoding request header to indicate the client supports HTTP // response compression using gzip return builder.build(); }
From source file:com.olacabs.fabric.processors.httpwriter.HttpWriter.java
private void setAuth(AuthConfiguration authConfiguration, HttpClientBuilder builder) throws InitializationException { if (!Strings.isNullOrEmpty(authConfiguration.getUsername())) { Credentials credentials = new UsernamePasswordCredentials(authConfiguration.getUsername(), authConfiguration.getPassword()); CredentialsProvider credentialsProvider = new BasicCredentialsProvider(); credentialsProvider.setCredentials(new AuthScope(AuthScope.ANY_HOST, AuthScope.ANY_PORT), credentials); builder.addInterceptorFirst((HttpRequestInterceptor) (request, context) -> { AuthState authState = (AuthState) context.getAttribute(HttpClientContext.TARGET_AUTH_STATE); if (authState.getAuthScheme() == null) { //log.debug("SETTING CREDS"); //log.info("Preemptive AuthState: {}", authState); authState.update(new BasicScheme(), credentials); }//from w ww .j ava 2 s.c om }); } else { log.error("Username can't be blank for basic auth."); throw new InitializationException("Username blank for basic auth"); } }
From source file:org.sonatype.nexus.internal.httpclient.HttpClientManagerImpl.java
@Override @Guarded(by = STARTED)//from w w w. java 2 s. co m public HttpClientBuilder prepare(@Nullable final Customizer customizer) { final HttpClientPlan plan = httpClientPlan(); // attach connection manager early, so customizer has chance to replace it if needed plan.getClient().setConnectionManager(sharedConnectionManager); // apply defaults defaultsCustomizer.customize(plan); // apply globals new ConfigurationCustomizer(getConfigurationInternal()).customize(plan); // apply instance customization if (customizer != null) { customizer.customize(plan); } // apply plan to builder HttpClientBuilder builder = plan.getClient(); // User agent must be set here to apply to all apache http requests, including over proxies String userAgent = plan.getUserAgent(); if (userAgent != null) { setUserAgent(builder, userAgent); } builder.setDefaultConnectionConfig(plan.getConnection().build()); builder.setDefaultSocketConfig(plan.getSocket().build()); builder.setDefaultRequestConfig(plan.getRequest().build()); builder.setDefaultCredentialsProvider(plan.getCredentials()); builder.addInterceptorFirst((HttpRequest request, HttpContext context) -> { // add custom http-context attributes for (Entry<String, Object> entry : plan.getAttributes().entrySet()) { // only set context attribute if not already set, to allow per request overrides if (context.getAttribute(entry.getKey()) == null) { context.setAttribute(entry.getKey(), entry.getValue()); } } // add custom http-request headers for (Entry<String, String> entry : plan.getHeaders().entrySet()) { request.addHeader(entry.getKey(), entry.getValue()); } }); builder.addInterceptorLast((HttpRequest httpRequest, HttpContext httpContext) -> { if (outboundLog.isDebugEnabled()) { httpContext.setAttribute(CTX_REQ_STOPWATCH, Stopwatch.createStarted()); httpContext.setAttribute(CTX_REQ_URI, getRequestURI(httpContext)); outboundLog.debug("{} > {}", httpContext.getAttribute(CTX_REQ_URI), httpRequest.getRequestLine()); } }); builder.addInterceptorLast((HttpResponse httpResponse, HttpContext httpContext) -> { Stopwatch stopwatch = (Stopwatch) httpContext.getAttribute(CTX_REQ_STOPWATCH); if (stopwatch != null) { outboundLog.debug("{} < {} @ {}", httpContext.getAttribute(CTX_REQ_URI), httpResponse.getStatusLine(), stopwatch); } }); return builder; }