List of usage examples for org.apache.http.protocol HttpContext setAttribute
void setAttribute(String str, Object obj);
From source file:com.urswolfer.gerrit.client.rest.http.GerritRestClient.java
private HttpClientBuilder getHttpClient(HttpContext httpContext) { HttpClientBuilder client = HttpClients.custom(); client.useSystemProperties(); // see also: com.intellij.util.net.ssl.CertificateManager OkHttpClient c = new OkHttpClient(); c.setFollowRedirects(true);//from ww w .jav a 2s . c o m // we need to get redirected result after login (which is done with POST) for extracting xGerritAuth client.setRedirectStrategy(new LaxRedirectStrategy()); c.setCookieHandler(cookieManager); c.setConnectTimeout(CONNECTION_TIMEOUT_MS, TimeUnit.MILLISECONDS); c.setReadTimeout(CONNECTION_TIMEOUT_MS, TimeUnit.MILLISECONDS); c.setWriteTimeout(CONNECTION_TIMEOUT_MS, TimeUnit.MILLISECONDS); CredentialsProvider credentialsProvider = getCredentialsProvider(); client.setDefaultCredentialsProvider(credentialsProvider); if (authData.isLoginAndPasswordAvailable()) { credentialsProvider.setCredentials(AuthScope.ANY, new UsernamePasswordCredentials(authData.getLogin(), authData.getPassword())); BasicScheme basicAuth = new BasicScheme(); httpContext.setAttribute(PREEMPTIVE_AUTH, basicAuth); client.addInterceptorFirst(new PreemptiveAuthHttpRequestInterceptor(authData)); } client.addInterceptorLast(new UserAgentHttpRequestInterceptor()); for (HttpClientBuilderExtension httpClientBuilderExtension : httpClientBuilderExtensions) { client = httpClientBuilderExtension.extend(client, authData); credentialsProvider = httpClientBuilderExtension.extendCredentialProvider(client, credentialsProvider, authData); } return client; }
From source file:com.mediatek.systemupdate.HttpManager.java
private HttpResponse doPost(String url, Map<String, String> headers, ArrayList<BasicNameValuePair> bnvpa) { Xlog.i(TAG, "doPost, url = " + url + ", mCookies = " + mCookies); HttpContext localcontext = new BasicHttpContext(); if (mCookies != null) { localcontext.setAttribute(ClientContext.COOKIE_STORE, mCookies); }/*from www. j ava 2 s . c o m*/ HttpResponse response = null; try { HttpHost host = null; HttpPost httpPost = null; if (url.contains("https")) { Uri uri = Uri.parse(url); host = new HttpHost(uri.getHost(), PORT_NUMBER, uri.getScheme()); httpPost = new HttpPost(uri.getPath()); } else { httpPost = new HttpPost(url); } if (headers != null) { for (Map.Entry<String, String> entry : headers.entrySet()) { httpPost.addHeader(entry.getKey(), entry.getValue()); } } if (bnvpa != null) { httpPost.setEntity(new UrlEncodedFormEntity(bnvpa)); } DefaultHttpClient httpClient = new DefaultHttpClient(mHttpConnMgr, mHttpParam); try { if (url.contains("https")) { Xlog.i(TAG, "doPost, https"); response = httpClient.execute(host, httpPost); } else { Xlog.i(TAG, "doPost, http"); Xlog.i(TAG, "mHttpClient =" + httpClient + "httpPost = " + httpPost + "localcontext = " + localcontext); response = httpClient.execute(httpPost, localcontext); } if (mCookies == null) { mCookies = httpClient.getCookieStore(); Xlog.i(TAG, "mCookies size = " + mCookies.getCookies().size()); } return response; } catch (ConnectTimeoutException e) { e.printStackTrace(); mErrorCode = HTTP_RESPONSE_NETWORK_ERROR; } } catch (UnsupportedEncodingException e) { e.printStackTrace(); mErrorCode = HTTP_RESPONSE_NETWORK_ERROR; } catch (IOException e) { e.printStackTrace(); mErrorCode = HTTP_RESPONSE_NETWORK_ERROR; } return response; }
From source file:org.jasig.schedassist.impl.caldav.CaldavCalendarDataDaoImpl.java
/** * Construct an {@link HttpContext} with a {@link CredentialsProvider} appropriate * for the {@link ICalendarAccount} argument. * Returned value is intended for use with {@link HttpClient#execute(HttpHost, HttpRequest, HttpContext)}. * // w ww. j a v a2 s. c o m * @param calendarAccount * @return an appropriate {@link HttpContext} for the {@link ICalendarAccount}. */ protected HttpContext constructHttpContext(ICalendarAccount calendarAccount) { CredentialsProvider credentialsProvider = this.credentialsProviderFactory .getCredentialsProvider(calendarAccount); HttpContext context = new BasicHttpContext(); if (isPreemptiveAuthenticationEnabled()) { if (preemptiveAuthenticationScheme == null) { throw new IllegalStateException( "preemptiveAuthentication is enabled, but the preemptiveAuthenticationScheme is null. Was afterPropertiesSet invoked?"); } context.setAttribute(PreemptiveAuthInterceptor.PREEMPTIVE_AUTH, preemptiveAuthenticationScheme); } context.setAttribute(ClientContext.CREDS_PROVIDER, credentialsProvider); return context; }
From source file:org.robolectric.shadows.httpclient.DefaultRequestDirector.java
/** * Creates a tunnel to the target server. * The connection must be established to the (last) proxy. * A CONNECT request for tunnelling through the proxy will * be created and sent, the response received and checked. * This method does <i>not</i> update the connection with * information about the tunnel, that is left to the caller. * * @param route the route to establish * @param context the context for request execution * * @return <code>true</code> if the tunnelled route is secure, * <code>false</code> otherwise. * The implementation here always returns <code>false</code>, * but derived classes may override. * * @throws HttpException in case of a problem * @throws IOException in case of an IO problem *//*from w ww . j a v a2 s . co m*/ protected boolean createTunnelToTarget(HttpRoute route, HttpContext context) throws HttpException, IOException { HttpHost proxy = route.getProxyHost(); HttpHost target = route.getTargetHost(); HttpResponse response = null; boolean done = false; while (!done) { done = true; if (!this.managedConn.isOpen()) { this.managedConn.open(route, context, this.params); } HttpRequest connect = createConnectRequest(route, context); connect.setParams(this.params); // Populate the execution context context.setAttribute(ExecutionContext.HTTP_TARGET_HOST, target); context.setAttribute(ExecutionContext.HTTP_PROXY_HOST, proxy); context.setAttribute(ExecutionContext.HTTP_CONNECTION, managedConn); context.setAttribute(ClientContext.TARGET_AUTH_STATE, targetAuthState); context.setAttribute(ClientContext.PROXY_AUTH_STATE, proxyAuthState); context.setAttribute(ExecutionContext.HTTP_REQUEST, connect); this.requestExec.preProcess(connect, this.httpProcessor, context); response = this.requestExec.execute(connect, this.managedConn, context); response.setParams(this.params); this.requestExec.postProcess(response, this.httpProcessor, context); int status = response.getStatusLine().getStatusCode(); if (status < 200) { throw new HttpException("Unexpected response to CONNECT request: " + response.getStatusLine()); } CredentialsProvider credsProvider = (CredentialsProvider) context .getAttribute(ClientContext.CREDS_PROVIDER); if (credsProvider != null && HttpClientParams.isAuthenticating(params)) { if (this.proxyAuthHandler.isAuthenticationRequested(response, context)) { this.log.debug("Proxy requested authentication"); Map<String, Header> challenges = this.proxyAuthHandler.getChallenges(response, context); try { processChallenges(challenges, this.proxyAuthState, this.proxyAuthHandler, response, context); } catch (AuthenticationException ex) { if (this.log.isWarnEnabled()) { this.log.warn("Authentication error: " + ex.getMessage()); break; } } updateAuthState(this.proxyAuthState, proxy, credsProvider); if (this.proxyAuthState.getCredentials() != null) { done = false; // Retry request if (this.reuseStrategy.keepAlive(response, context)) { this.log.debug("Connection kept alive"); // Consume response content HttpEntity entity = response.getEntity(); if (entity != null) { entity.consumeContent(); } } else { this.managedConn.close(); } } } else { // Reset proxy auth scope this.proxyAuthState.setAuthScope(null); } } } int status = response.getStatusLine().getStatusCode(); // can't be null if (status > 299) { // Buffer response content HttpEntity entity = response.getEntity(); if (entity != null) { response.setEntity(new BufferedHttpEntity(entity)); } this.managedConn.close(); throw new TunnelRefusedException("CONNECT refused by proxy: " + response.getStatusLine(), response); } this.managedConn.markReusable(); // How to decide on security of the tunnelled connection? // The socket factory knows only about the segment to the proxy. // Even if that is secure, the hop to the target may be insecure. // Leave it to derived classes, consider insecure by default here. return false; }
From source file:de.escidoc.core.common.business.fedora.FedoraUtility.java
/** * Makes a HTTP GET request to Fedora URL expanded by given local URL. * /* www . ja va 2s. com*/ * @param localUrl * The Fedora local URL. Should start with the '/' after the webcontext path (usually "fedora"). E.g. if * http://localhost:8080/fedora/get/... then localUrl is /get/... * @return MimeInputStream for content of the URL Request. * @throws WebserverSystemException * If an error occurs. */ public MimeInputStream requestMimeFedoraURL(final String localUrl) throws WebserverSystemException { final MimeInputStream fedoraResponseStream = new MimeInputStream(); try { final DefaultHttpClient httpClient = getHttpClient(); final HttpContext localcontext = new BasicHttpContext(); final BasicScheme basicAuth = new BasicScheme(); localcontext.setAttribute("preemptive-auth", basicAuth); httpClient.addRequestInterceptor(new PreemptiveAuthInterceptor(), 0); final HttpGet httpGet = new HttpGet(this.fedoraUrl + localUrl); final HttpResponse httpResponse = httpClient.execute(httpGet); final int responseCode = httpResponse.getStatusLine().getStatusCode(); if (httpResponse.getFirstHeader("Content-Type") != null) { fedoraResponseStream.setMimeType(httpResponse.getFirstHeader("Content-Type").getValue()); } if (responseCode != HttpServletResponse.SC_OK) { EntityUtils.consume(httpResponse.getEntity()); throw new WebserverSystemException( "Bad response code '" + responseCode + "' requesting '" + this.fedoraUrl + localUrl + "'.", new FedoraSystemException(httpResponse.getStatusLine().getReasonPhrase())); } fedoraResponseStream.setInputStream(httpResponse.getEntity().getContent()); } catch (final IOException e) { throw new WebserverSystemException(e); } return fedoraResponseStream; }
From source file:org.vietspider.net.apache.DefaultRequestDirector.java
/** * Creates a tunnel to the target server. * The connection must be established to the (last) proxy. * A CONNECT request for tunnelling through the proxy will * be created and sent, the response received and checked. * This method does <i>not</i> update the connection with * information about the tunnel, that is left to the caller. * * @param route the route to establish * @param context the context for request execution * * @return <code>true</code> if the tunnelled route is secure, * <code>false</code> otherwise. * The implementation here always returns <code>false</code>, * but derived classes may override. * * @throws HttpException in case of a problem * @throws IOException in case of an IO problem *//* w w w . j a v a 2 s .c om*/ protected boolean createTunnelToTarget(HttpRoute route, HttpContext context) throws HttpException, IOException { HttpHost proxy = route.getProxyHost(); HttpHost target = route.getTargetHost(); HttpResponse response = null; boolean done = false; while (!done) { done = true; if (!this.managedConn.isOpen()) { this.managedConn.open(route, context, this.params); } HttpRequest connect = createConnectRequest(route, context); connect.setParams(this.params); // Populate the execution context context.setAttribute(ExecutionContext.HTTP_TARGET_HOST, target); context.setAttribute(ExecutionContext.HTTP_PROXY_HOST, proxy); context.setAttribute(ExecutionContext.HTTP_CONNECTION, managedConn); context.setAttribute(ClientContext.TARGET_AUTH_STATE, targetAuthState); context.setAttribute(ClientContext.PROXY_AUTH_STATE, proxyAuthState); context.setAttribute(ExecutionContext.HTTP_REQUEST, connect); this.requestExec.preProcess(connect, this.httpProcessor, context); response = this.requestExec.execute(connect, this.managedConn, context); response.setParams(this.params); this.requestExec.postProcess(response, this.httpProcessor, context); int status = response.getStatusLine().getStatusCode(); if (status < 200) { throw new HttpException("Unexpected response to CONNECT request: " + response.getStatusLine()); } CredentialsProvider credsProvider = (CredentialsProvider) context .getAttribute(ClientContext.CREDS_PROVIDER); if (credsProvider != null && HttpClientParams.isAuthenticating(params)) { if (this.proxyAuthHandler.isAuthenticationRequested(response, context)) { this.log.debug("Proxy requested authentication"); Map<String, Header> challenges = this.proxyAuthHandler.getChallenges(response, context); try { processChallenges(challenges, this.proxyAuthState, this.proxyAuthHandler, response, context); } catch (AuthenticationException ex) { if (this.log.isWarnEnabled()) { this.log.warn("Authentication error: " + ex.getMessage()); break; } } updateAuthState(this.proxyAuthState, proxy, credsProvider); if (this.proxyAuthState.getCredentials() != null) { done = false; // Retry request if (this.reuseStrategy.keepAlive(response, context)) { this.log.debug("Connection kept alive"); // Consume response content HttpEntity entity = response.getEntity(); EntityUtils.consume(entity); } else { this.managedConn.close(); } } } else { // Reset proxy auth scope this.proxyAuthState.setAuthScope(null); } } } int status = response.getStatusLine().getStatusCode(); // can't be null if (status > 299) { // Buffer response content HttpEntity entity = response.getEntity(); if (entity != null) { response.setEntity(new BufferedHttpEntity(entity)); } this.managedConn.close(); throw new TunnelRefusedException("CONNECT refused by proxy: " + response.getStatusLine(), response); } this.managedConn.markReusable(); // How to decide on security of the tunnelled connection? // The socket factory knows only about the segment to the proxy. // Even if that is secure, the hop to the target may be insecure. // Leave it to derived classes, consider insecure by default here. return false; }
From source file:org.opensaml.security.httpclient.impl.SecurityEnhancedTLSSocketFactory.java
/** * Perform trust evaluation by extracting the server TLS {@link X509Credential} from the * {@link SSLSession} and evaluating it via a {@link TrustEngine<Credential>} * and {@link CriteriaSet} supplied by the caller via the {@link HttpContext}. * /*from w ww .java2 s. c om*/ * @param socket the socket instance being processed * @param context the HttpClient context being processed * * @throws IOException if the server TLS credential is untrusted, or if there is a fatal error * attempting trust evaluation. */ protected void performTrustEval(@Nonnull final Socket socket, @Nonnull final HttpContext context) throws IOException { if (!(socket instanceof SSLSocket)) { log.debug("Socket was not an instance of SSLSocket, skipping trust eval"); return; } SSLSocket sslSocket = (SSLSocket) socket; log.debug("Attempting to evaluate server TLS credential against supplied TrustEngine and CriteriaSet"); @SuppressWarnings("unchecked") TrustEngine<? super X509Credential> trustEngine = (TrustEngine<? super X509Credential>) context .getAttribute(HttpClientSecurityConstants.CONTEXT_KEY_TRUST_ENGINE); if (trustEngine == null) { log.debug("No trust engine supplied by caller, skipping trust eval"); return; } else { log.trace("Saw trust engine of type: {}", trustEngine.getClass().getName()); } CriteriaSet criteriaSet = (CriteriaSet) context .getAttribute(HttpClientSecurityConstants.CONTEXT_KEY_CRITERIA_SET); if (criteriaSet == null) { log.debug("No criteria set supplied by caller, building new criteria set with signing criteria"); criteriaSet = new CriteriaSet(new UsageCriterion(UsageType.SIGNING)); } else { log.trace("Saw CriteriaSet: {}", criteriaSet); } X509Credential credential = extractCredential(sslSocket); try { if (trustEngine.validate(credential, criteriaSet)) { log.debug("Credential evaluated as trusted"); context.setAttribute(HttpClientSecurityConstants.CONTEXT_KEY_SERVER_TLS_CREDENTIAL_TRUSTED, Boolean.TRUE); } else { log.debug("Credential evaluated as untrusted"); context.setAttribute(HttpClientSecurityConstants.CONTEXT_KEY_SERVER_TLS_CREDENTIAL_TRUSTED, Boolean.FALSE); throw new SSLPeerUnverifiedException( "Trust engine could not establish trust of server TLS credential"); } } catch (SecurityException e) { log.error("Trust engine error evaluating credential", e); throw new IOException("Trust engine error evaluating credential", e); } }