List of usage examples for org.apache.http.protocol HttpContext getAttribute
Object getAttribute(String str);
From source file:gsn.http.rest.RestRemoteWrapper.java
public DataField[] connectToRemote() throws IOException, ClassNotFoundException { // Create the GET request HttpGet httpget = new HttpGet(initParams.getRemoteContactPointEncoded(lastReceivedTimestamp)); // Create local execution context HttpContext localContext = new BasicHttpContext(); ///* w ww .jav a 2 s.co m*/ structure = null; int tries = 0; AuthState authState = null; // if (inputStream != null) { try { if (response != null && response.getEntity() != null) { response.getEntity().consumeContent(); } inputStream.close(); inputStream = null; } catch (Exception e) { logger.debug(e.getMessage(), e); } } // while (tries < 2) { tries++; try { // Execute the GET request response = httpclient.execute(httpget, localContext); // int sc = response.getStatusLine().getStatusCode(); // if (sc == HttpStatus.SC_OK) { logger.debug(new StringBuilder().append("Wants to consume the structure packet from ") .append(initParams.getRemoteContactPoint()).toString()); inputStream = XSTREAM.createObjectInputStream(response.getEntity().getContent()); structure = (DataField[]) inputStream.readObject(); logger.warn("Connection established for: " + initParams.getRemoteContactPoint()); break; } else { if (sc == HttpStatus.SC_UNAUTHORIZED) authState = (AuthState) localContext.getAttribute(ClientContext.TARGET_AUTH_STATE); // Target host authentication required else if (sc == HttpStatus.SC_PROXY_AUTHENTICATION_REQUIRED) authState = (AuthState) localContext.getAttribute(ClientContext.PROXY_AUTH_STATE); // Proxy authentication required else { logger.error(new StringBuilder().append("Unexpected GET status code returned: ").append(sc) .append("\nreason: ").append(response.getStatusLine().getReasonPhrase()) .toString()); } if (authState != null) { if (initParams.getUsername() == null || (tries > 1 && initParams.getUsername() != null)) { logger.error("A valid username/password required to connect to the remote host: " + initParams.getRemoteContactPoint()); } else { AuthScope authScope = authState.getAuthScope(); logger.warn(new StringBuilder().append("Setting Credentials for host: ") .append(authScope.getHost()).append(":").append(authScope.getPort()) .toString()); Credentials creds = new UsernamePasswordCredentials(initParams.getUsername(), initParams.getPassword()); httpclient.getCredentialsProvider().setCredentials(authScope, creds); } } } } catch (RuntimeException ex) { // In case of an unexpected exception you may want to abort // the HTTP request in order to shut down the underlying // connection and release it back to the connection manager. logger.warn("Aborting the HTTP GET request."); httpget.abort(); throw ex; } finally { if (structure == null) { if (response != null && response.getEntity() != null) { response.getEntity().consumeContent(); } } } } if (structure == null) throw new RuntimeException("Cannot connect to the remote host: " + initParams.getRemoteContactPoint()); return structure; }
From source file:com.googlecode.jdeltasync.DeltaSyncClient.java
private <T> T post(final IDeltaSyncSession session, String uri, final String userAgent, final String contentType, final byte[] data, final UriCapturingResponseHandler<T> handler) throws DeltaSyncException, IOException { final HttpPost post = createHttpPost(uri, userAgent, contentType, data); final HttpContext context = new BasicHttpContext(); context.setAttribute(HttpClientContext.COOKIE_STORE, session.getCookieStore()); try {/*from w w w . j a v a 2 s . c o m*/ return httpClient.execute(post, new ResponseHandler<T>() { public T handleResponse(HttpResponse response) throws ClientProtocolException, IOException { try { if (isRedirect(response)) { URI redirectUri = getRedirectLocationURI(session, post, response, context); return post(session, redirectUri.toString(), userAgent, contentType, data, handler); } if (response.getStatusLine().getStatusCode() != HttpStatus.SC_OK) { throw new HttpException(response.getStatusLine().getStatusCode(), response.getStatusLine().getReasonPhrase()); } HttpRequest request = (HttpRequest) context.getAttribute(HttpCoreContext.HTTP_REQUEST); HttpHost host = (HttpHost) context.getAttribute(HttpCoreContext.HTTP_TARGET_HOST); URI uri; try { if (request instanceof HttpUriRequest) { uri = ((HttpUriRequest) request).getURI(); } else { uri = new URI(request.getRequestLine().getUri()); } if (!uri.isAbsolute()) { uri = URIUtils.rewriteURI(uri, host); } } catch (URISyntaxException e) { throw new DeltaSyncException(e); } return handler.handle(uri, response); } catch (DeltaSyncException e) { throw new RuntimeException(e); } } }, context); } catch (RuntimeException e) { Throwable t = e.getCause(); while (t != null) { if (t instanceof DeltaSyncException) { throw (DeltaSyncException) t; } t = t.getCause(); } throw e; } }
From source file:fi.okm.mpass.shibboleth.monitor.FormPostTargetResolver.java
/** {@inheritDoc} */ public SequenceStep resolve(final HttpContext context, final SequenceStep startingStep) throws ResponseValidatorException { if (parameters != null) { log.debug("Adding the step parameters {}", parameters); for (final NameValuePair parameter : parameters) { startingStep.getParameters().add(parameter); }//from w w w .j a v a 2s .c o m } final SequenceResponse response = resolveStep(context, startingStep, isFollowRedirects()); final String redirectUrl = getHeaderValue(response.getHeaders(), "Location"); if (!isFollowRedirects() && redirectUrl != null) { final SequenceStep resultStep = new SequenceStep(); resultStep.setUrl(completeUrl(context, redirectUrl)); return resultStep; } final String result = response.getResponse(); if (StringSupport.trimOrNull(result) == null) { throw new ResponseValidatorException("The response is empty!"); } final SequenceStep resultStep = initResultStep(); final List<NameValuePair> resultParameters = new ArrayList<>(); final String action = getValue(result, "action"); log.debug("Parsed action {}", action); for (final String item : outputParameters) { final String value = getParamValue(result, item); if (value != null) { resultParameters.add(new BasicNameValuePair(item, StringEscapeUtils.unescapeHtml(value))); } } if (action != null) { final String url = action.replaceAll(":", ":").replaceAll("/", "/"); resultStep.setUrl(url); if (!url.startsWith("http")) { final HttpHost target = (HttpHost) context.getAttribute(HttpCoreContext.HTTP_TARGET_HOST); resultStep.setUrl( target.getSchemeName() + "://" + target.getHostName() + ":" + target.getPort() + url); } else { resultStep.setUrl(url); } } if (resultParameters.size() > 0) { resultStep.setParameters(resultParameters); } return resultStep; }
From source file:org.apache.synapse.transport.nhttp.ClientHandler.java
private void setHeaders(HttpContext context, HttpResponse response, MessageContext outMsgCtx, MessageContext responseMsgCtx) { Header[] headers = response.getAllHeaders(); if (headers != null && headers.length > 0) { Map<String, String> headerMap = new TreeMap<String, String>(new Comparator<String>() { public int compare(String o1, String o2) { return o1.compareToIgnoreCase(o2); }//w ww. ja v a 2 s . c om }); String endpointURLPrefix = (String) context.getAttribute(NhttpConstants.ENDPOINT_PREFIX); String servicePrefix = (String) outMsgCtx.getProperty(NhttpConstants.SERVICE_PREFIX); for (int i = 0; i < headers.length; i++) { Header header = headers[i]; // if this header is already added if (headerMap.containsKey(header.getName())) { /* this is a multi-value header */ // generate the key String key = NhttpConstants.EXCESS_TRANSPORT_HEADERS; // get the old value String oldValue = headerMap.get(header.getName()); // adds additional values to a list in a property of message // context Map map; if (responseMsgCtx.getProperty(key) != null) { map = (Map) responseMsgCtx.getProperty(key); map.put(header.getName(), oldValue); } else { map = new MultiValueMap(); map.put(header.getName(), oldValue); // set as a property in message context responseMsgCtx.setProperty(key, map); } } if ("Location".equals(header.getName()) && endpointURLPrefix != null && servicePrefix != null) { // Here, we are changing only the host name and the port of // the new URI - value of the Location // header. // If the new URI is again referring to a resource in the // server to which the original request // is sent, then replace the hostname and port of the URI // with the hostname and port of synapse // We are not changing the request url here, only the host // name and the port. try { URI serviceURI = new URI(servicePrefix); URI endpointURI = new URI(endpointURLPrefix); URI locationURI = new URI(header.getValue()); if (locationURI.getHost().equalsIgnoreCase(endpointURI.getHost())) { URI newURI = new URI(locationURI.getScheme(), locationURI.getUserInfo(), serviceURI.getHost(), serviceURI.getPort(), locationURI.getPath(), locationURI.getQuery(), locationURI.getFragment()); headerMap.put(header.getName(), newURI.toString()); responseMsgCtx.setProperty(NhttpConstants.SERVICE_PREFIX, outMsgCtx.getProperty(NhttpConstants.SERVICE_PREFIX)); } } catch (URISyntaxException e) { log.error(e.getMessage(), e); } } else { headerMap.put(header.getName(), header.getValue()); } } responseMsgCtx.setProperty(MessageContext.TRANSPORT_HEADERS, headerMap); } }
From source file:com.jobaline.uiautomation.framework.selenium.phantomJsThreeHourTimeoutFix.HttpCommandExecutor.java
private Response createResponse(HttpResponse httpResponse, HttpContext context, EntityWithEncoding entityWithEncoding) throws IOException { final Response response; Header header = httpResponse.getFirstHeader("Content-Type"); if (header != null && header.getValue().startsWith("application/json")) { String responseAsText = entityWithEncoding.getContentString(); try {/* w ww .j a v a2s .c o m*/ response = new JsonToBeanConverter().convert(Response.class, responseAsText); } catch (ClassCastException e) { if (responseAsText != null && "".equals(responseAsText)) { // The remote server has died, but has already set some headers. // Normally this occurs when the final window of the firefox driver // is closed on OS X. Return null, as the return value _should_ be // being ignored. This is not an elegant solution. return null; } throw new WebDriverException("Cannot convert text to response: " + responseAsText, e); } } else { response = new Response(); if (header != null && header.getValue().startsWith("image/png")) { response.setValue(entityWithEncoding.getContent()); } else if (entityWithEncoding.hasEntityContent()) { response.setValue(entityWithEncoding.getContentString()); } HttpHost finalHost = (HttpHost) context.getAttribute(HTTP_TARGET_HOST); String uri = finalHost.toURI(); String sessionId = HttpSessionId.getSessionId(uri); if (sessionId != null) { response.setSessionId(sessionId); } int statusCode = httpResponse.getStatusLine().getStatusCode(); if (!(statusCode > 199 && statusCode < 300)) { // 4xx represents an unknown command or a bad request. if (statusCode > 399 && statusCode < 500) { response.setStatus(ErrorCodes.UNKNOWN_COMMAND); } else if (statusCode > 499 && statusCode < 600) { // 5xx represents an internal server error. The response status should already be set, but // if not, set it to a general error code. if (response.getStatus() == ErrorCodes.SUCCESS) { response.setStatus(ErrorCodes.UNHANDLED_ERROR); } } else { response.setStatus(ErrorCodes.UNHANDLED_ERROR); } } if (response.getValue() instanceof String) { // We normalise to \n because Java will translate this to \r\n // if this is suitable on our platform, and if we have \r\n, java will // turn this into \r\r\n, which would be Bad! response.setValue(((String) response.getValue()).replace("\r\n", "\n")); } } response.setState(errorCodes.toState(response.getStatus())); return response; }
From source file:com.akop.bach.parser.Parser.java
protected String getResponse(HttpUriRequest request, List<NameValuePair> inputs) throws IOException, ParserException { if (!request.containsHeader("Accept")) request.addHeader("Accept", "text/javascript, text/html, application/xml, text/xml, */*"); if (!request.containsHeader("Accept-Charset")) request.addHeader("Accept-Charset", "ISO-8859-1,utf-8;q=0.7,*;q=0.7"); if (App.getConfig().logToConsole()) App.logv("Parser: Fetching %s", request.getURI()); long started = System.currentTimeMillis(); initRequest(request);/*from ww w . ja va 2 s . c o m*/ try { synchronized (mHttpClient) { HttpContext context = new BasicHttpContext(); StringBuilder log = null; if (App.getConfig().logHttp()) { log = new StringBuilder(); log.append(String.format("URL: %s\n", request.getURI())); log.append("Headers: \n"); for (Header h : request.getAllHeaders()) log.append(String.format(" '%s': '%s'\n", h.getName(), h.getValue())); log.append("Cookies: \n"); for (Cookie c : mHttpClient.getCookieStore().getCookies()) log.append(String.format(" '%s': '%s'\n", c.getName(), c.getValue())); log.append("Query Elements: \n"); if (inputs != null) { for (NameValuePair p : inputs) log.append(String.format(" '%s': '%s'\n", p.getName(), p.getValue())); } else { log.append(" [empty]\n"); } } try { mLastResponse = mHttpClient.execute(request, context); } catch (SocketTimeoutException e) { throw new ParserException(mContext, R.string.error_timed_out); } try { if (mLastResponse.getStatusLine().getStatusCode() == HttpStatus.SC_OK) { HttpUriRequest currentReq = (HttpUriRequest) context .getAttribute(ExecutionContext.HTTP_REQUEST); HttpHost currentHost = (HttpHost) context.getAttribute(ExecutionContext.HTTP_TARGET_HOST); this.mLastUrl = currentHost.toURI() + currentReq.getURI(); } } catch (Exception e) { if (App.getConfig().logToConsole()) { App.logv("Unable to get last URL - see stack:"); e.printStackTrace(); } this.mLastUrl = null; } HttpEntity entity = mLastResponse.getEntity(); if (entity == null) return null; InputStream stream = entity.getContent(); BufferedReader reader = new BufferedReader(new InputStreamReader(stream), 10000); StringBuilder builder = new StringBuilder(10000); try { int read; char[] buffer = new char[1000]; while ((read = reader.read(buffer)) >= 0) builder.append(buffer, 0, read); } catch (OutOfMemoryError e) { return null; } stream.close(); entity.consumeContent(); String response; try { response = builder.toString(); } catch (OutOfMemoryError e) { if (App.getConfig().logToConsole()) e.printStackTrace(); return null; } if (App.getConfig().logHttp()) { log.append(String.format("\nResponse: \n%s\n", response)); writeToFile( generateDatedFilename( "http-log-" + request.getURI().toString().replaceAll("[^A-Za-z0-9]", "_")), log.toString()); } return preparseResponse(response); } } finally { if (App.getConfig().logToConsole()) displayTimeTaken("Parser: Fetch took", started); } }
From source file:org.sonatype.nexus.httpclient.NexusRedirectStrategy.java
@Override public boolean isRedirected(final HttpRequest request, final HttpResponse response, final HttpContext context) throws ProtocolException { if (super.isRedirected(request, response, context)) { // code below comes from DefaultRedirectStrategy, as method super.getLocationURI cannot be used // since it modifies context state, and would result in false circular reference detection final Header locationHeader = response.getFirstHeader("location"); if (locationHeader == null) { // got a redirect response, but no location header throw new ProtocolException( "Received redirect response " + response.getStatusLine() + " but no location present"); }/*w w w . j a va 2s. c o m*/ // Some complication here as it appears that something may be null, but its not clear what was null final URI sourceUri = ((HttpUriRequest) request).getURI(); final String sourceScheme = schemeOf(sourceUri); final String sourceHost = hostOf(sourceUri); final URI targetUri = createLocationURI(locationHeader.getValue()); final String targetScheme = schemeOf(targetUri); final String targetHost = hostOf(targetUri); // nag about redirection peculiarities, in any case if (!Objects.equals(sourceScheme, targetScheme)) { if ("http".equals(targetScheme)) { // security risk: HTTPS > HTTP downgrade, you are not safe as you think! log.debug("Downgrade from HTTPS to HTTP during redirection {} -> {}", sourceUri, targetUri); } else if ("https".equals(targetScheme) && Objects.equals(sourceHost, targetHost)) { // misconfiguration: your repository configured with wrong protocol and causes performance problems? log.debug("Protocol upgrade during redirection on same host {} -> {}", sourceUri, targetUri); } } // this logic below should trigger only for content fetches made by RRS retrieveItem // hence, we do this ONLY if the HttpRequest is "marked" as such request if (Boolean.TRUE == context.getAttribute(CONTENT_RETRIEVAL_MARKER_KEY)) { if (targetUri.getPath().endsWith("/")) { log.debug("Not following redirection to index {} -> {}", sourceUri, targetUri); return false; } } log.debug("Following redirection {} -> {}", sourceUri, targetUri); return true; } return false; }
From source file:com.sangupta.jerry.http.WebResponseHandler.java
/** * @see org.apache.http.client.ResponseHandler#handleResponse(org.apache.http.HttpResponse) *///from w w w .j ava 2 s . c om @Override public WebResponse handleResponse(HttpResponse response, HttpContext localHttpContext) throws ClientProtocolException, IOException { StatusLine statusLine = response.getStatusLine(); HttpEntity entity = response.getEntity(); byte[] bytes = null; if (entity != null) { bytes = EntityUtils.toByteArray(entity); } final WebResponse webResponse = new WebResponse(bytes); // decipher from status line webResponse.responseCode = statusLine.getStatusCode(); webResponse.message = statusLine.getReasonPhrase(); // set size if (entity != null) { webResponse.size = entity.getContentLength(); } else { long value = 0; Header header = response.getFirstHeader(HttpHeaders.CONTENT_LENGTH); if (header != null) { String headerValue = header.getValue(); if (AssertUtils.isNotEmpty(headerValue)) { try { value = Long.parseLong(headerValue); } catch (Exception e) { // eat the exception } } } webResponse.size = value; } // content type if (entity != null && entity.getContentType() != null) { webResponse.contentType = entity.getContentType().getValue(); } // response headers final Header[] responseHeaders = response.getAllHeaders(); if (AssertUtils.isNotEmpty(responseHeaders)) { for (Header header : responseHeaders) { webResponse.headers.put(header.getName(), header.getValue()); } } // charset try { ContentType type = ContentType.get(entity); if (type != null) { webResponse.charSet = type.getCharset(); } } catch (UnsupportedCharsetException e) { // we are unable to find the charset for the content // let's leave it to be considered binary } // fill in the redirect uri chain RedirectLocations locations = (RedirectLocations) localHttpContext .getAttribute(HttpClientContext.REDIRECT_LOCATIONS); if (AssertUtils.isNotEmpty(locations)) { webResponse.setRedirectChain(locations.getAll()); } // return the object finally return webResponse; }
From source file:com.grendelscan.commons.http.apache_overrides.client.CustomClientRequestDirector.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. * //w w w .jav a 2 s .co m * @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 */ private 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 (!managedConn.isOpen()) { managedConn.open(route, context, params); } HttpRequest connect = createConnectRequest(route); connect.setParams(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); requestExec.preProcess(connect, httpProcessor, context); response = requestExec.execute(connect, managedConn, context); response.setParams(params); requestExec.postProcess(response, 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 (proxyAuthHandler.isAuthenticationRequested(response, context)) { LOGGER.debug("Proxy requested authentication"); Map<String, Header> challenges = proxyAuthHandler.getChallenges(response, context); try { processChallenges(challenges, proxyAuthState, proxyAuthHandler, response, context); } catch (AuthenticationException ex) { LOGGER.warn("Authentication error: " + ex.getMessage()); } updateAuthState(proxyAuthState, proxy, credsProvider); if (proxyAuthState.getCredentials() != null) { done = false; // Retry request if (reuseStrategy.keepAlive(response, context)) { LOGGER.debug("Connection kept alive"); // Consume response content HttpEntity entity = response.getEntity(); if (entity != null) { entity.consumeContent(); } } else { managedConn.close(); } } } else { // Reset proxy auth scope 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)); } managedConn.close(); throw new TunnelRefusedException("CONNECT refused by proxy: " + response.getStatusLine(), response); } 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:com.android.tools.idea.sdk.remote.internal.UrlOpener.java
@NonNull private static Pair<InputStream, HttpResponse> openWithHttpClient(@NonNull String url, @NonNull ITaskMonitor monitor, Header[] inHeaders) throws IOException, CanceledByUserException { UserCredentials result = null;//from w w w.j a va 2 s.c o m String realm = null; HttpParams params = new BasicHttpParams(); HttpConnectionParams.setConnectionTimeout(params, sConnectionTimeoutMs); HttpConnectionParams.setSoTimeout(params, sSocketTimeoutMs); // use the simple one final DefaultHttpClient httpClient = new DefaultHttpClient(params); // create local execution context HttpContext localContext = new BasicHttpContext(); final HttpGet httpGet = new HttpGet(url); if (inHeaders != null) { for (Header header : inHeaders) { httpGet.addHeader(header); } } // retrieve local java configured network in case there is the need to // authenticate a proxy ProxySelectorRoutePlanner routePlanner = new ProxySelectorRoutePlanner( httpClient.getConnectionManager().getSchemeRegistry(), ProxySelector.getDefault()); httpClient.setRoutePlanner(routePlanner); // Set preference order for authentication options. // In particular, we don't add AuthPolicy.SPNEGO, which is given preference over NTLM in // servers that support both, as it is more secure. However, we don't seem to handle it // very well, so we leave it off the list. // See http://hc.apache.org/httpcomponents-client-ga/tutorial/html/authentication.html for // more info. List<String> authpref = new ArrayList<String>(); authpref.add(AuthPolicy.BASIC); authpref.add(AuthPolicy.DIGEST); authpref.add(AuthPolicy.NTLM); httpClient.getParams().setParameter(AuthPNames.PROXY_AUTH_PREF, authpref); httpClient.getParams().setParameter(AuthPNames.TARGET_AUTH_PREF, authpref); if (DEBUG) { try { URI uri = new URI(url); ProxySelector sel = routePlanner.getProxySelector(); if (sel != null && uri.getScheme().startsWith("httP")) { //$NON-NLS-1$ List<Proxy> list = sel.select(uri); System.out.printf("SdkLib.UrlOpener:\n Connect to: %s\n Proxy List: %s\n", //$NON-NLS-1$ url, list == null ? "(null)" : Arrays.toString(list.toArray()));//$NON-NLS-1$ } } catch (Exception e) { System.out.printf("SdkLib.UrlOpener: Failed to get proxy info for %s: %s\n", //$NON-NLS-1$ url, e.toString()); } } boolean trying = true; // loop while the response is being fetched while (trying) { // connect and get status code HttpResponse response = httpClient.execute(httpGet, localContext); int statusCode = response.getStatusLine().getStatusCode(); if (DEBUG) { System.out.printf(" Status: %d\n", statusCode); //$NON-NLS-1$ } // check whether any authentication is required AuthState authenticationState = null; if (statusCode == HttpStatus.SC_UNAUTHORIZED) { // Target host authentication required authenticationState = (AuthState) localContext.getAttribute(ClientContext.TARGET_AUTH_STATE); } if (statusCode == HttpStatus.SC_PROXY_AUTHENTICATION_REQUIRED) { // Proxy authentication required authenticationState = (AuthState) localContext.getAttribute(ClientContext.PROXY_AUTH_STATE); } if (statusCode == HttpStatus.SC_OK || statusCode == HttpStatus.SC_NOT_MODIFIED) { // in case the status is OK and there is a realm and result, // cache it if (realm != null && result != null) { sRealmCache.put(realm, result); } } // there is the need for authentication if (authenticationState != null) { // get scope and realm AuthScope authScope = authenticationState.getAuthScope(); // If the current realm is different from the last one it means // a pass was performed successfully to the last URL, therefore // cache the last realm if (realm != null && !realm.equals(authScope.getRealm())) { sRealmCache.put(realm, result); } realm = authScope.getRealm(); // in case there is cache for this Realm, use it to authenticate if (sRealmCache.containsKey(realm)) { result = sRealmCache.get(realm); } else { // since there is no cache, request for login and password result = monitor.displayLoginCredentialsPrompt("Site Authentication", "Please login to the following domain: " + realm + "\n\nServer requiring authentication:\n" + authScope.getHost()); if (result == null) { throw new CanceledByUserException("User canceled login dialog."); } } // retrieve authentication data String user = result.getUserName(); String password = result.getPassword(); String workstation = result.getWorkstation(); String domain = result.getDomain(); // proceed in case there is indeed a user if (user != null && user.length() > 0) { Credentials credentials = new NTCredentials(user, password, workstation, domain); httpClient.getCredentialsProvider().setCredentials(authScope, credentials); trying = true; } else { trying = false; } } else { trying = false; } HttpEntity entity = response.getEntity(); if (entity != null) { if (trying) { // in case another pass to the Http Client will be performed, close the entity. entity.getContent().close(); } else { // since no pass to the Http Client is needed, retrieve the // entity's content. // Note: don't use something like a BufferedHttpEntity since it would consume // all content and store it in memory, resulting in an OutOfMemory exception // on a large download. InputStream is = new FilterInputStream(entity.getContent()) { @Override public void close() throws IOException { // Since Http Client is no longer needed, close it. // Bug #21167: we need to tell http client to shutdown // first, otherwise the super.close() would continue // downloading and not return till complete. httpClient.getConnectionManager().shutdown(); super.close(); } }; HttpResponse outResponse = new BasicHttpResponse(response.getStatusLine()); outResponse.setHeaders(response.getAllHeaders()); outResponse.setLocale(response.getLocale()); return Pair.of(is, outResponse); } } else if (statusCode == HttpStatus.SC_NOT_MODIFIED) { // It's ok to not have an entity (e.g. nothing to download) for a 304 HttpResponse outResponse = new BasicHttpResponse(response.getStatusLine()); outResponse.setHeaders(response.getAllHeaders()); outResponse.setLocale(response.getLocale()); return Pair.of(null, outResponse); } } // We get here if we did not succeed. Callers do not expect a null result. httpClient.getConnectionManager().shutdown(); throw new FileNotFoundException(url); }