List of usage examples for org.apache.http.impl.client DefaultHttpClient addRequestInterceptor
public synchronized void addRequestInterceptor(final HttpRequestInterceptor itcp, final int index)
From source file:cloudMe.CloudMeAPI.java
private DefaultHttpClient getConnection() { DefaultHttpClient httpClient = new DefaultHttpClient(); HttpProtocolParams.setUseExpectContinue(httpClient.getParams(), false); HttpProtocolParams.setUserAgent(httpClient.getParams(), USER_AGENT_INFO); httpClient.getCredentialsProvider().setCredentials(new AuthScope(host, 80, "os@xcerion.com", "Digest"), new UsernamePasswordCredentials(userName, pass)); // Encrypts password & username HttpRequestInterceptor preemptiveAuth = new HttpRequestInterceptor() { public void process(final HttpRequest request, final HttpContext context) throws HttpException, IOException { AuthState authState = (AuthState) context.getAttribute(ClientContext.TARGET_AUTH_STATE); if (authState.getAuthScheme() == null) { if (creds != null && scheme != null) { authState.setAuthScheme(scheme); authState.setCredentials(creds); } else { scheme = authState.getAuthScheme(); }// w w w .ja va 2 s. c o m } } }; httpClient.addRequestInterceptor(preemptiveAuth, 0); return httpClient; }
From source file:de.mendelson.comm.as2.send.MessageHttpUploader.java
/**Sets necessary HTTP authentication for this partner, depending on if it is an asny MDN that will be sent or an AS2 message. *If the partner is not configured to use HTTP authentication in any kind nothing will happen in here *//*from w ww . j a v a 2s .c o m*/ private void setHTTPAuthentication(DefaultHttpClient client, Partner receiver, boolean isMDN) { HTTPAuthentication authentication = null; if (isMDN) { authentication = receiver.getAuthenticationAsyncMDN(); } else { authentication = receiver.getAuthentication(); } if (authentication.isEnabled()) { Credentials userPassCredentials = new UsernamePasswordCredentials(authentication.getUser(), authentication.getPassword()); client.getCredentialsProvider().setCredentials(AuthScope.ANY, userPassCredentials); BasicHttpContext localcontext = new BasicHttpContext(); // Generate BASIC scheme object and stick it to the local // execution context BasicScheme basicAuth = new BasicScheme(); localcontext.setAttribute("preemptive-auth", basicAuth); // Add as the first request interceptor client.addRequestInterceptor(new PreemptiveAuth(), 0); } }
From source file:org.orbeon.oxf.resources.handler.HTTPURLConnection.java
public void connect() throws IOException { if (!connected) { final String userInfo = url.getUserInfo(); final boolean isAuthenticationRequestedWithUsername = username != null && !username.equals(""); // Create the HTTP client and HTTP context for the client (we expect this to be fairly lightweight) final DefaultHttpClient httpClient = new DefaultHttpClient(connectionManager, httpParams); final HttpContext httpContext = new BasicHttpContext(); // Set cookie store, creating a new one if none was provided to us if (cookieStore == null) cookieStore = new BasicCookieStore(); httpClient.setCookieStore(cookieStore); // Set proxy and host authentication if (proxyAuthState != null) httpContext.setAttribute(ClientContext.PROXY_AUTH_STATE, proxyAuthState); if (userInfo != null || isAuthenticationRequestedWithUsername) { // Make authentication preemptive; interceptor is added first, as the Authentication header is added // by HttpClient's RequestTargetAuthentication which is itself an interceptor, so our interceptor // needs to run before RequestTargetAuthentication, otherwise RequestTargetAuthentication won't find // the appropriate AuthState/AuthScheme/Credentials in the HttpContext // Don't add the interceptor if we don't want preemptive authentication! if (!"false".equals(preemptiveAuthentication)) { httpClient.addRequestInterceptor(preemptiveAuthHttpRequestInterceptor, 0); }//from ww w . j a va 2s. c o m CredentialsProvider credentialsProvider = new BasicCredentialsProvider(); httpContext.setAttribute(ClientContext.CREDS_PROVIDER, credentialsProvider); final AuthScope authScope = new AuthScope(url.getHost(), url.getPort()); final Credentials credentials; if (userInfo != null) { // Set username and optional password specified on URL final int separatorPosition = userInfo.indexOf(":"); String username = separatorPosition == -1 ? userInfo : userInfo.substring(0, separatorPosition); String password = separatorPosition == -1 ? "" : userInfo.substring(separatorPosition + 1); // If the username/password contain special character, those character will be encoded, since we // are getting this from a URL. Now do the decoding. username = URLDecoder.decode(username, "utf-8"); password = URLDecoder.decode(password, "utf-8"); credentials = new UsernamePasswordCredentials(username, password); } else { // Set username and password specified externally credentials = domain == null ? new UsernamePasswordCredentials(username, password == null ? "" : password) : new NTCredentials(username, password, url.getHost(), domain); } credentialsProvider.setCredentials(authScope, credentials); } // If method has not been set, use GET // This can happen e.g. when this connection handler is used from URLFactory if (method == null) setRequestMethod("GET"); // Set all headers, final boolean skipAuthorizationHeader = userInfo != null || username != null; for (final Map.Entry<String, String[]> currentEntry : requestProperties.entrySet()) { final String currentHeaderName = currentEntry.getKey(); final String[] currentHeaderValues = currentEntry.getValue(); for (final String currentHeaderValue : currentHeaderValues) { // Skip over Authorization header if user authentication specified if (skipAuthorizationHeader && currentHeaderName.toLowerCase() .equals(Connection.AUTHORIZATION_HEADER.toLowerCase())) continue; method.addHeader(currentHeaderName, currentHeaderValue); } } // Create request entity with body if (method instanceof HttpEntityEnclosingRequest) { // Use the body that was set directly, or the result of writing to the OutputStream final byte[] body = (requestBody != null) ? requestBody : (os != null) ? os.toByteArray() : null; if (body != null) { final Header contentTypeHeader = method.getFirstHeader("Content-Type"); // Header names are case-insensitive for comparison if (contentTypeHeader == null) throw new ProtocolException("Can't set request entity: Content-Type header is missing"); final ByteArrayEntity byteArrayEntity = new ByteArrayEntity(body); byteArrayEntity.setContentType(contentTypeHeader); ((HttpEntityEnclosingRequest) method).setEntity(byteArrayEntity); } } // Make request httpResponse = httpClient.execute(method, httpContext); connected = true; } }
From source file:de.escidoc.core.common.business.fedora.FedoraUtility.java
/** * Makes a HTTP GET request to Fedora URL expanded by given local URL. * /*from ww w . j a va2 s . c o m*/ * @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.apache.manifoldcf.crawler.connectors.generic.GenericConnector.java
protected DefaultHttpClient getClient() throws ManifoldCFException { DefaultHttpClient cl = new DefaultHttpClient(); if (genericLogin != null && !genericLogin.isEmpty()) { try {// w w w . j a va2s . co m URL url = new URL(genericEntryPoint); Credentials credentials = new UsernamePasswordCredentials(genericLogin, genericPassword); cl.getCredentialsProvider().setCredentials( new AuthScope(url.getHost(), url.getPort() > 0 ? url.getPort() : 80, AuthScope.ANY_REALM), credentials); cl.addRequestInterceptor(new PreemptiveAuth(credentials), 0); } catch (MalformedURLException ex) { throw new ManifoldCFException("getClient exception: " + ex.getMessage(), ex); } } HttpConnectionParams.setConnectionTimeout(cl.getParams(), connectionTimeoutMillis); HttpConnectionParams.setSoTimeout(cl.getParams(), socketTimeoutMillis); return cl; }
From source file:de.escidoc.core.common.util.service.ConnectionUtility.java
/** * Set Authentication to a given {@link DefaultHttpClient} instance. * //from w w w . j av a 2 s . c om * @param url * URL of resource. * @param username * User name for authentication * @param password * Password for authentication. * @throws WebserverSystemException * Thrown if connection failed. */ public void setAuthentication(final DefaultHttpClient client, final URL url, final String username, final String password) { final CredentialsProvider credsProvider = new BasicCredentialsProvider(); final AuthScope authScope = new AuthScope(url.getHost(), AuthScope.ANY_PORT, AuthScope.ANY_REALM); final Credentials creds = new UsernamePasswordCredentials(username, password); credsProvider.setCredentials(authScope, creds); client.setCredentialsProvider(credsProvider); // don't wait for auth request final HttpRequestInterceptor preemptiveAuth = new HttpRequestInterceptor() { @Override public void process(final HttpRequest request, final HttpContext context) { final AuthState authState = (AuthState) context.getAttribute(ClientContext.TARGET_AUTH_STATE); final CredentialsProvider credsProvider = (CredentialsProvider) context .getAttribute(ClientContext.CREDS_PROVIDER); final HttpHost targetHost = (HttpHost) context.getAttribute(ExecutionContext.HTTP_TARGET_HOST); // If not auth scheme has been initialized yet if (authState.getAuthScheme() == null) { final AuthScope authScope = new AuthScope(targetHost.getHostName(), targetHost.getPort()); // Obtain credentials matching the target host final Credentials creds = credsProvider.getCredentials(authScope); // If found, generate BasicScheme preemptively if (creds != null) { authState.setAuthScheme(new BasicScheme()); authState.setCredentials(creds); } } } }; client.addRequestInterceptor(preemptiveAuth, 0); }