List of usage examples for org.apache.http.client.protocol HttpClientContext adapt
public static HttpClientContext adapt(final HttpContext context)
From source file:org.apache.sling.testing.clients.interceptors.StickyCookieInterceptor.java
public void process(HttpRequest httpRequest, HttpContext httpContext) throws HttpException, IOException { final HttpClientContext clientContext = HttpClientContext.adapt(httpContext); List<Cookie> cookies = clientContext.getCookieStore().getCookies(); boolean set = (null != StickyCookieHolder.getTestStickySessionCookie()); boolean found = false; ListIterator<Cookie> it = cookies.listIterator(); while (it.hasNext()) { Cookie cookie = it.next();//from ww w . j av a 2 s . c o m if (cookie.getName().equals(StickyCookieHolder.COOKIE_NAME)) { found = true; if (set) { // set the cookie with the value saved for each thread using the rule it.set(StickyCookieHolder.getTestStickySessionCookie()); } else { // if the cookie is not set in TestStickySessionRule, remove it from here it.remove(); } } } // if the cookie needs to be set from TestStickySessionRule but did not exist in the client cookie list, add it here. if (!found && set) { cookies.add(StickyCookieHolder.getTestStickySessionCookie()); } BasicCookieStore cs = new BasicCookieStore(); cs.addCookies(cookies.toArray(new Cookie[cookies.size()])); httpContext.setAttribute(HttpClientContext.COOKIE_STORE, cs); }
From source file:org.artifactory.util.PreemptiveAuthInterceptor.java
@Override public void process(HttpRequest request, HttpContext context) throws HttpException, IOException { HttpClientContext clientContext = HttpClientContext.adapt(context); AuthState authState = clientContext.getTargetAuthState(); // If there's no auth scheme available yet, try to initialize it preemptively if (authState.getAuthScheme() == null) { CredentialsProvider credsProvider = clientContext.getCredentialsProvider(); HttpHost targetHost = clientContext.getTargetHost(); Credentials creds = credsProvider .getCredentials(new AuthScope(targetHost.getHostName(), targetHost.getPort())); if (creds == null) { log.debug("No credentials found for host " + targetHost); } else {//from w w w. j a v a 2 s.c om log.debug("Updating credentials for host " + targetHost); authState.update(new BasicScheme(), creds); } } }
From source file:org.sonatype.nexus.httpclient.PreemptiveAuthHttpRequestInterceptor.java
@Override public void process(final HttpRequest request, final HttpContext context) throws HttpException, IOException { HttpClientContext clientContext = HttpClientContext.adapt(context); AuthState authState = clientContext.getTargetAuthState(); if (authState.getAuthScheme() == null) { CredentialsProvider credsProvider = clientContext.getCredentialsProvider(); HttpHost targetHost = clientContext.getTargetHost(); Credentials creds = credsProvider .getCredentials(new AuthScope(targetHost.getHostName(), targetHost.getPort())); if (creds != null) { authState.update(new BasicScheme(), creds); }/*ww w. ja v a2s .c o m*/ } }
From source file:org.artifactory.util.ProxyPreemptiveAuthInterceptor.java
@Override public void process(HttpRequest request, HttpContext context) throws HttpException, IOException { HttpClientContext clientContext = HttpClientContext.adapt(context); AuthState proxyAuthState = clientContext.getProxyAuthState(); // If there's no auth scheme available yet, try to initialize it preemptively if (proxyAuthState.getAuthScheme() == null) { CredentialsProvider credsProvider = clientContext.getCredentialsProvider(); RouteInfo route = clientContext.getHttpRoute(); if (route == null) { log.debug("No route found for {}", clientContext.getTargetHost()); return; }/*from w w w . j ava2 s . c o m*/ HttpHost proxyHost = route.getProxyHost(); if (proxyHost == null) { log.warn("No proxy host found in route {} for host {}", route, clientContext.getTargetHost()); return; } Credentials creds = credsProvider .getCredentials(new AuthScope(proxyHost.getHostName(), proxyHost.getPort())); if (creds == null) { log.info("No credentials found for proxy: " + proxyHost); return; } proxyAuthState.update(new BasicScheme(ChallengeState.PROXY), creds); } }
From source file:org.sonatype.nexus.apachehttpclient.PreemptiveAuthHttpRequestInterceptor.java
@Override public void process(final HttpRequest request, final HttpContext context) throws HttpException, IOException { final HttpClientContext clientContext = HttpClientContext.adapt(context); final AuthState authState = clientContext.getTargetAuthState(); if (authState.getAuthScheme() == null) { final CredentialsProvider credsProvider = clientContext.getCredentialsProvider(); final HttpHost targetHost = clientContext.getTargetHost(); final Credentials creds = credsProvider .getCredentials(new AuthScope(targetHost.getHostName(), targetHost.getPort())); if (creds != null) { authState.update(new BasicScheme(), creds); }/*from ww w .j a va2 s . co m*/ } }
From source file:cn.wanghaomiao.seimi.http.hc.HttpClientFactory.java
public static HttpClientBuilder cliBuilder(int timeout) { HttpRequestRetryHandler retryHander = new HttpRequestRetryHandler() { @Override/*w w w . ja v a 2 s . co m*/ 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 java.net.SocketTimeoutException) { //? return true; } if (exception instanceof InterruptedIOException) { // Timeout return true; } if (exception instanceof UnknownHostException) { // Unknown host 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; } }; RedirectStrategy redirectStrategy = new SeimiRedirectStrategy(); RequestConfig requestConfig = RequestConfig.custom().setConnectTimeout(timeout).setSocketTimeout(timeout) .build(); PoolingHttpClientConnectionManager poolingHttpClientConnectionManager = HttpClientConnectionManagerProvider .getHcPoolInstance(); return HttpClients.custom().setDefaultRequestConfig(requestConfig) .setConnectionManager(poolingHttpClientConnectionManager).setRedirectStrategy(redirectStrategy) .setRetryHandler(retryHander); }
From source file:microsoft.exchange.webservices.data.CookieProcessingTargetAuthenticationStrategy.java
@Override public Map<String, Header> getChallenges(HttpHost authhost, HttpResponse response, HttpContext context) throws MalformedChallengeException { try {//from w ww .ja v a 2 s. c o m // Get the request from the context HttpClientContext clientContext = HttpClientContext.adapt(context); HttpRequest request = clientContext.getRequest(); // Save new cookies in the context responseProcessCookies.process(response, context); // Remove existing cookies and set the new cookies in the request request.removeHeaders("Cookie"); requestAddCookies.process(request, context); } catch (HttpException e) { throw new RuntimeException(e); // Looking at the source of responseProcessCookies this never happens } catch (IOException e) { throw new RuntimeException(e); // Looking at the source of responseProcessCookies this never happens } return super.getChallenges(authhost, response, context); }
From source file:org.tinymediamanager.scraper.util.TmmHttpClient.java
/** * instantiates a new CloseableHttpClient * /*ww w. j a va2 s .c om*/ * @return CloseableHttpClient */ public static CloseableHttpClient createHttpClient() { PoolingHttpClientConnectionManager connectionManager = new PoolingHttpClientConnectionManager(); // Increase default max connection per route to 5 connectionManager.setMaxTotal(5); HttpClientBuilder httpClientBuilder = HttpClients.custom().useSystemProperties(); httpClientBuilder.setConnectionManager(connectionManager); // my own retry handler HttpRequestRetryHandler myRetryHandler = new HttpRequestRetryHandler() { @Override public boolean retryRequest(IOException exception, int executionCount, HttpContext context) { if (executionCount >= 5) { // 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; } }; httpClientBuilder.setRetryHandler(myRetryHandler); // set proxy if needed if ((Globals.settings.useProxy())) { setProxy(httpClientBuilder); } return httpClientBuilder.build(); }
From source file:RestApiHttpClient.java
/** * Create an new {@link RestApiHttpClient} instance with Endpoint, username and API-Key * //from ww w . j a va 2 s .co m * @param apiEndpoint The Hostname and Api-Endpoint (http://www.example.com/api) * @param username Shopware Username * @param password Api-Key from User-Administration */ public RestApiHttpClient(URL apiEndpoint, String username, String password) { this.apiEndpoint = apiEndpoint; BasicHttpContext context = new BasicHttpContext(); this.localContext = HttpClientContext.adapt(context); HttpHost target = new HttpHost(this.apiEndpoint.getHost(), -1, this.apiEndpoint.getProtocol()); this.localContext.setTargetHost(target); TargetAuthenticationStrategy authStrat = new TargetAuthenticationStrategy(); UsernamePasswordCredentials creds = new UsernamePasswordCredentials(username, password); BasicCredentialsProvider credsProvider = new BasicCredentialsProvider(); AuthScope aScope = new AuthScope(target.getHostName(), target.getPort()); credsProvider.setCredentials(aScope, creds); BasicAuthCache authCache = new BasicAuthCache(); // Digest Authentication DigestScheme digestAuth = new DigestScheme(Charset.forName("UTF-8")); authCache.put(target, digestAuth); this.localContext.setAuthCache(authCache); this.localContext.setCredentialsProvider(credsProvider); ArrayList<Header> defHeaders = new ArrayList<>(); defHeaders.add(new BasicHeader(HttpHeaders.ACCEPT, ContentType.APPLICATION_JSON.getMimeType())); this.httpclient = HttpClients.custom().useSystemProperties().setTargetAuthenticationStrategy(authStrat) .disableRedirectHandling() // make Rest-API Endpoint GZIP-Compression enable comment this out // Response-Compression is also possible .disableContentCompression().setDefaultHeaders(defHeaders) .setDefaultCredentialsProvider(credsProvider).build(); }
From source file:me.ixfan.wechatkit.token.ObtainTokenRetryHandler.java
@Override public boolean retryRequest(IOException exception, int executionCount, HttpContext context) { if (executionCount > MAX_RETRY_TIME) { logger.warn("?? access token " + MAX_RETRY_TIME + " , ?."); return false; }//from w w w . j a v a 2 s . c o m if (exception instanceof InterruptedIOException) { logger.warn("?? access token ."); return false; } if (exception instanceof UnknownHostException) { logger.error("?, API ??."); return false; } if (exception instanceof ConnectTimeoutException) { logger.error("? access token ?."); return false; } if (exception instanceof SSLException) { logger.error("SSL ."); return false; } HttpClientContext clientContext = HttpClientContext.adapt(context); HttpRequest request = clientContext.getRequest(); boolean idempotent = !(request instanceof HttpEntityEnclosingRequest); if (idempotent) { return true; } return false; }