List of usage examples for org.apache.http.client.protocol HttpClientContext create
public static HttpClientContext create()
From source file:com.baidubce.http.BceHttpClient.java
/** * Creates HttpClient Context object based on the internal request. * * @param request The internal request./*ww w . j ava2 s . c om*/ * @return HttpClient Context object. */ protected HttpClientContext createHttpContext(InternalRequest request) { HttpClientContext context = HttpClientContext.create(); context.setRequestConfig( this.requestConfigBuilder.setExpectContinueEnabled(request.isExpectContinueEnabled()).build()); if (this.credentialsProvider != null) { context.setCredentialsProvider(this.credentialsProvider); } if (this.config.isProxyPreemptiveAuthenticationEnabled()) { AuthCache authCache = new BasicAuthCache(); authCache.put(this.proxyHttpHost, new BasicScheme()); context.setAuthCache(authCache); } return context; }
From source file:org.opensaml.soap.client.http.AbstractPipelineHttpSOAPClient.java
/** * Resolve the effective {@link HttpClientContext} instance to use for the current request. * //from w w w. jav a 2s . c o m * @param operationContext the current operation context * @return the effective client context instance to use */ @Nonnull protected HttpClientContext resolveHttpContext(InOutOperationContext operationContext) { HttpClientRequestContext requestContext = operationContext.getOutboundMessageContext() .getSubcontext(HttpClientRequestContext.class, false); if (requestContext != null && requestContext.getHttpClientContext() != null) { return requestContext.getHttpClientContext(); } else { return HttpClientContext.create(); } }
From source file:org.alfresco.dataprep.UserService.java
/** * Login in alfresco share// w w w .j a va 2 s.c o m * * @param userName login user name * @param userPass login user password * @return true for successful user login */ public HttpState login(final String userName, final String userPass) { if (StringUtils.isEmpty(userName) || StringUtils.isEmpty(userPass)) { throw new IllegalArgumentException("Parameter missing"); } AlfrescoHttpClient client = alfrescoHttpClientFactory.getObject(); HttpState state = null; org.apache.commons.httpclient.HttpClient theClient = new org.apache.commons.httpclient.HttpClient(); String reqURL = client.getShareUrl() + "share/page/dologin"; org.apache.commons.httpclient.methods.PostMethod post = new org.apache.commons.httpclient.methods.PostMethod( reqURL); NameValuePair[] formParams; CookieStore cookieStore = new BasicCookieStore(); HttpClientContext localContext = HttpClientContext.create(); localContext.setCookieStore(cookieStore); formParams = (new NameValuePair[] { new NameValuePair("username", userName), new NameValuePair("password", userPass), new NameValuePair("success", "/share/page/user/" + userName + "/dashboard"), new NameValuePair("failure", "/share/page/type/login?error=true") }); post.setRequestBody(formParams); try { int postStatus = theClient.executeMethod(post); if (302 == postStatus) { state = theClient.getState(); post.releaseConnection(); org.apache.commons.httpclient.methods.GetMethod get = new org.apache.commons.httpclient.methods.GetMethod( client.getShareUrl() + "share/page/user/" + userName + "/dashboard"); theClient.setState(state); theClient.executeMethod(get); get.releaseConnection(); } } catch (IOException e) { throw new RuntimeException("Failed to execute the request"); } return state; }
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 {//w w w . j a v a 2s .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.bonitasoft.connectors.rest.RESTConnector.java
/** * Set the builder based on the request elements * /*from w w w. j ava 2s . c o m*/ * @param requestConfigurationBuilder The builder to be set * @param authorization The authentication element of the request * @param proxy The proxy element of the request * @param urlHost The URL host of the request * @param urlPort The URL post of the request * @param urlProtocol The URL protocol of the request * @param httpClientBuilder The builder to be set * @return HTTPContext The HTTP context to be set */ private HttpContext setAuthorizations(final Builder requestConfigurationBuilder, final Authorization authorization, final Proxy proxy, final String urlHost, final int urlPort, final String urlProtocol, final HttpClientBuilder httpClientBuilder) { HttpContext httpContext = HttpClientContext.create(); if (authorization != null) { if (authorization instanceof BasicDigestAuthorization) { final BasicDigestAuthorization castAuthorization = (BasicDigestAuthorization) authorization; final List<String> authPrefs = new ArrayList<>(); if (castAuthorization.isBasic()) { authPrefs.add(AuthSchemes.BASIC); } else { authPrefs.add(AuthSchemes.DIGEST); } requestConfigurationBuilder.setTargetPreferredAuthSchemes(authPrefs); final String username = castAuthorization.getUsername(); final String password = new String(castAuthorization.getPassword()); String host = urlHost; if (isStringInputValid(castAuthorization.getHost())) { host = castAuthorization.getHost(); } int port = urlPort; if (castAuthorization.getPort() != null) { port = castAuthorization.getPort(); } String realm = AuthScope.ANY_REALM; if (isStringInputValid(castAuthorization.getRealm())) { realm = castAuthorization.getRealm(); } final CredentialsProvider credentialsProvider = new BasicCredentialsProvider(); credentialsProvider.setCredentials(new AuthScope(host, port, realm), new UsernamePasswordCredentials(username, password)); setProxyCrendentials(proxy, credentialsProvider); httpClientBuilder.setDefaultCredentialsProvider(credentialsProvider); if (castAuthorization.isPreemptive() || proxy != null) { final AuthCache authoriationCache = new BasicAuthCache(); if (castAuthorization.isPreemptive()) { AuthSchemeBase authorizationScheme = null; if (castAuthorization.isBasic()) { authorizationScheme = new BasicScheme(ChallengeState.TARGET); } else { authorizationScheme = new DigestScheme(ChallengeState.TARGET); } authoriationCache.put(new HttpHost(host, port, urlProtocol), authorizationScheme); } if (proxy != null) { final BasicScheme basicScheme = new BasicScheme(ChallengeState.PROXY); authoriationCache.put(new HttpHost(proxy.getHost(), proxy.getPort()), basicScheme); } final HttpClientContext localContext = HttpClientContext.create(); localContext.setAuthCache(authoriationCache); httpContext = localContext; } } } else if (proxy != null) { final CredentialsProvider credentialsProvider = new BasicCredentialsProvider(); setProxyCrendentials(proxy, credentialsProvider); httpClientBuilder.setDefaultCredentialsProvider(credentialsProvider); // Make it preemptive if (proxy.hasCredentials()) { final AuthCache authoriationCache = new BasicAuthCache(); final BasicScheme basicScheme = new BasicScheme(ChallengeState.PROXY); authoriationCache.put(new HttpHost(proxy.getHost(), proxy.getPort()), basicScheme); final HttpClientContext localContext = HttpClientContext.create(); localContext.setAuthCache(authoriationCache); httpContext = localContext; } } return httpContext; }
From source file:com.rabbitmq.http.client.Client.java
private HttpComponentsClientHttpRequestFactory getRequestFactory(final URL url, final String username, final String password, final SSLConnectionSocketFactory sslConnectionSocketFactory, final SSLContext sslContext) throws MalformedURLException { String theUser = username;/* w ww. j a v a 2 s. c om*/ String thePassword = password; String userInfo = url.getUserInfo(); if (userInfo != null && theUser == null) { String[] userParts = userInfo.split(":"); if (userParts.length > 0) { theUser = userParts[0]; } if (userParts.length > 1) { thePassword = userParts[1]; } } final HttpClientBuilder bldr = HttpClientBuilder.create() .setDefaultCredentialsProvider(getCredentialsProvider(url, theUser, thePassword)); bldr.setDefaultHeaders(Arrays.asList(new BasicHeader(HttpHeaders.CONTENT_TYPE, "application/json"))); if (sslConnectionSocketFactory != null) { bldr.setSSLSocketFactory(sslConnectionSocketFactory); } if (sslContext != null) { bldr.setSslcontext(sslContext); } HttpClient httpClient = bldr.build(); // RabbitMQ HTTP API currently does not support challenge/response for PUT methods. AuthCache authCache = new BasicAuthCache(); BasicScheme basicScheme = new BasicScheme(); authCache.put(new HttpHost(rootUri.getHost(), rootUri.getPort(), rootUri.getScheme()), basicScheme); final HttpClientContext ctx = HttpClientContext.create(); ctx.setAuthCache(authCache); return new HttpComponentsClientHttpRequestFactory(httpClient) { @Override protected HttpContext createHttpContext(HttpMethod httpMethod, URI uri) { return ctx; } }; }
From source file:com.lehman.ic9.net.httpClient.java
/** * Performs the actual HTTP request. This method is called from the GET and POST * methods. //from w ww . j av a2s. c o m * @param getString is a boolean flag with true for string and false for binary. * @param post is a boolean flag with true for post and false for get. * @return A Javascript object with the results of the request. * @throws ic9exception Exception * @throws NoSuchMethodException Exception * @throws ScriptException Exception */ private Map<String, Object> performRequest(boolean getString, httpReqType reqType) throws ic9exception, NoSuchMethodException, ScriptException { Map<String, Object> ret = this.eng.newObj(null); HttpRequestBase httpReq = null; if (reqType == httpReqType.GET) httpReq = new HttpGet(this.u.toString()); else if (reqType == httpReqType.POST) httpReq = new HttpPost(this.u.toString()); else if (reqType == httpReqType.PUT) httpReq = new HttpPut(this.u.toString()); else if (reqType == httpReqType.DELETE) httpReq = new HttpDelete(this.u.toString()); // Set cookies from JS object. this.cs.clear(); Object[] jscookies = (Object[]) this.eng.getJavaArray(this.jsobj.get("cookies")); for (Object tobj : jscookies) { @SuppressWarnings("unchecked") Map<String, Object> cobj = (Map<String, Object>) tobj; this.cs.addCookie(this.setApacheCookie(cobj)); } HttpClientContext ctx = HttpClientContext.create(); ctx.setCookieStore(this.cs); ctx.setCredentialsProvider(this.cp); ctx.setRequestConfig(this.rcb.build()); // Set headers. @SuppressWarnings("unchecked") Map<String, Object> headers = (Map<String, Object>) this.jsobj.get("headers"); for (String key : headers.keySet()) { String val = (String) headers.get(key); httpReq.addHeader(key, val); } CloseableHttpResponse resp = null; try { if (this.cli == null) { this.buildClient(httpReq); } if (reqType == httpReqType.POST && this.respEnt != null) ((HttpPost) httpReq).setEntity(this.respEnt); else if (reqType == httpReqType.PUT && this.respEnt != null) ((HttpPut) httpReq).setEntity(this.respEnt); resp = this.cli.execute(httpReq, ctx); HttpEntity ent = resp.getEntity(); this.getResponseInfo(ret, resp); if (ent != null) { if (getString) ret.put("content", this.getContentString(ent.getContent())); else { Map<String, Object> obj = this.eng.newObj("Buffer"); obj.put("data", this.getContentBinary(ent.getContent())); ret.put("content", obj); } EntityUtils.consume(ent); } } catch (ClientProtocolException e) { throw new ic9exception("httpClient.performRequest(): Client protocol exception. " + e.getMessage()); } catch (IOException e) { throw new ic9exception("httpClient.performRequest(): IO exception. " + e.getMessage()); } catch (KeyManagementException e) { throw new ic9exception("httpClient.performRequest(): Key management exception. " + e.getMessage()); } catch (NoSuchAlgorithmException e) { throw new ic9exception("httpClient.performRequest(): No such algorithm exception. " + e.getMessage()); } catch (KeyStoreException e) { throw new ic9exception("httpClient.performRequest(): Key store exception. " + e.getMessage()); } catch (AuthenticationException e) { throw new ic9exception("httpClient.performRequest(): Authentication exception. " + e.getMessage()); } catch (Exception e) { e.printStackTrace(); throw new ic9exception("httpClient.performRequest(): Unhandled exception. " + e.getMessage()); } finally { // Reset credentials if (this.creds != null) { this.creds = null; this.atype = authType.NONE; } if (resp != null) { try { resp.close(); } catch (IOException e) { } } if (reqType == httpReqType.POST || reqType == httpReqType.PUT) this.respEnt = null; } // Release the connection. httpReq.releaseConnection(); return ret; }
From source file:com.cloudbees.jenkins.plugins.bitbucket.client.BitbucketCloudApiClient.java
private void setClientProxyParams(String host, HttpClientBuilder builder) { Jenkins jenkins = Jenkins.getInstance(); ProxyConfiguration proxyConfig = null; if (jenkins != null) { proxyConfig = jenkins.proxy;/*from w w w. j ava2 s .c o m*/ } Proxy proxy = Proxy.NO_PROXY; if (proxyConfig != null) { proxy = proxyConfig.createProxy(host); } if (proxy.type() != Proxy.Type.DIRECT) { final InetSocketAddress proxyAddress = (InetSocketAddress) proxy.address(); LOGGER.fine("Jenkins proxy: " + proxy.address()); builder.setProxy(new HttpHost(proxyAddress.getHostName(), proxyAddress.getPort())); String username = proxyConfig.getUserName(); String password = proxyConfig.getPassword(); if (username != null && !"".equals(username.trim())) { LOGGER.fine("Using proxy authentication (user=" + username + ")"); CredentialsProvider credentialsProvider = new BasicCredentialsProvider(); credentialsProvider.setCredentials(AuthScope.ANY, new UsernamePasswordCredentials(username, password)); AuthCache authCache = new BasicAuthCache(); authCache.put(HttpHost.create(proxyAddress.getHostName()), new BasicScheme()); context = HttpClientContext.create(); context.setCredentialsProvider(credentialsProvider); context.setAuthCache(authCache); } } }