Example usage for org.apache.http.client.protocol HttpClientContext REDIRECT_LOCATIONS

List of usage examples for org.apache.http.client.protocol HttpClientContext REDIRECT_LOCATIONS

Introduction

In this page you can find the example usage for org.apache.http.client.protocol HttpClientContext REDIRECT_LOCATIONS.

Prototype

String REDIRECT_LOCATIONS

To view the source code for org.apache.http.client.protocol HttpClientContext REDIRECT_LOCATIONS.

Click Source Link

Document

Attribute name of a List object that represents a collection of all redirect locations received in the process of request execution.

Usage

From source file:com.sangupta.jerry.http.WebResponseHandler.java

/**
 * @see org.apache.http.client.ResponseHandler#handleResponse(org.apache.http.HttpResponse)
 *//*from   w w  w . ja va 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:de.shadowhunt.subversion.internal.AbstractOperation.java

/**
 * as the Resource can not differ between files and directories each request for an directory (without ending '/')
 * will result in a redirect (with ending '/'), if another call to a redirected URI occurs a
 * CircularRedirectException is thrown, as we can't determine the real target we can't prevent this from happening.
 * Allowing circular redirects globally could lead to live locks on the other hand. Therefore we clear the
 * redirection cache explicitly.//from  w  w  w  . j  a  v  a2  s.  c  o  m
 */
final void clearRedirects(final HttpContext context) {
    context.removeAttribute(HttpClientContext.REDIRECT_LOCATIONS);
}

From source file:com.amos.tool.SelfRedirectStrategy.java

public URI getLocationURI(final HttpRequest request, final HttpResponse response, final HttpContext context)
        throws ProtocolException {
    Args.notNull(request, "HTTP request");
    Args.notNull(response, "HTTP response");
    Args.notNull(context, "HTTP context");

    final HttpClientContext clientContext = HttpClientContext.adapt(context);

    //get the location header to find out where to redirect to
    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 header");
    }/*from  www . ja va2s.co  m*/
    final String location = locationHeader.getValue();
    if (this.log.isDebugEnabled()) {
        this.log.debug("Redirect requested to location '" + location + "'");
    }

    final RequestConfig config = clientContext.getRequestConfig();

    URI uri = createLocationURI(location.replaceAll(" ", "%20"));

    // rfc2616 demands the location value be a complete URI
    // Location       = "Location" ":" absoluteURI
    try {
        if (!uri.isAbsolute()) {
            if (!config.isRelativeRedirectsAllowed()) {
                throw new ProtocolException("Relative redirect location '" + uri + "' not allowed");
            }
            // Adjust location URI
            final HttpHost target = clientContext.getTargetHost();
            Asserts.notNull(target, "Target host");
            final URI requestURI = new URI(request.getRequestLine().getUri());
            final URI absoluteRequestURI = URIUtils.rewriteURI(requestURI, target, false);
            uri = URIUtils.resolve(absoluteRequestURI, uri);
        }
    } catch (final URISyntaxException ex) {
        throw new ProtocolException(ex.getMessage(), ex);
    }

    RedirectLocations redirectLocations = (RedirectLocations) clientContext
            .getAttribute(HttpClientContext.REDIRECT_LOCATIONS);
    if (redirectLocations == null) {
        redirectLocations = new RedirectLocations();
        context.setAttribute(HttpClientContext.REDIRECT_LOCATIONS, redirectLocations);
    }
    if (!config.isCircularRedirectsAllowed()) {
        if (redirectLocations.contains(uri)) {
            throw new CircularRedirectException("Circular redirect to '" + uri + "'");
        }
    }
    redirectLocations.add(uri);
    return uri;
}

From source file:com.frochr123.helper.CachedFileDownloader.java

public static SimpleEntry<String, ByteArrayOutputStream> getResultFromURL(String url) throws IOException {
    SimpleEntry<String, ByteArrayOutputStream> result = null;
    String finalUrl = null;//from www  . j  a  va2  s .  co  m
    ByteArrayOutputStream outputStream = null;

    if (url == null || url.isEmpty()) {
        return null;
    }

    // Create HTTP client and cusomized config for timeouts
    CloseableHttpClient httpClient = HttpClients.createDefault();
    RequestConfig requestConfig = RequestConfig.custom().setSocketTimeout(CACHE_DOWNLOADER_DEFAULT_TIMEOUT)
            .setConnectTimeout(CACHE_DOWNLOADER_DEFAULT_TIMEOUT)
            .setConnectionRequestTimeout(CACHE_DOWNLOADER_DEFAULT_TIMEOUT).build();

    // Create HTTP Get request
    HttpGet httpGet = new HttpGet(url);
    httpGet.setConfig(requestConfig);

    // Create context
    HttpContext context = new BasicHttpContext();

    // Check for temporary FabQR download of own configured private FabQR instance
    // In that case Authorization needs to be added
    if (FabQRFunctions.getFabqrPrivateURL() != null && !FabQRFunctions.getFabqrPrivateURL().isEmpty()
            && url.startsWith(FabQRFunctions.getFabqrPrivateURL())
            && url.contains("/" + FabQRFunctions.FABQR_TEMPORARY_MARKER + "/")) {
        // Set authentication information
        String encodedCredentials = Helper.getEncodedCredentials(FabQRFunctions.getFabqrPrivateUser(),
                FabQRFunctions.getFabqrPrivatePassword());
        if (!encodedCredentials.isEmpty()) {
            httpGet.addHeader("Authorization", "Basic " + encodedCredentials);
        }
    }

    // Send request
    CloseableHttpResponse response = httpClient.execute(httpGet, context);

    // Get all redirected locations from context, if there are any
    RedirectLocations redirectLocations = (RedirectLocations) (context
            .getAttribute(HttpClientContext.REDIRECT_LOCATIONS));
    if (redirectLocations != null) {
        finalUrl = redirectLocations.getAll().get(redirectLocations.getAll().size() - 1).toString();
    } else {
        finalUrl = url;
    }

    // Check response valid and max file size
    if (response.getEntity() == null
            || response.getEntity().getContentLength() > CACHE_DOWNLOADER_MAX_FILESIZE_BYTES) {
        return null;
    }

    // Get data
    outputStream = new ByteArrayOutputStream();
    response.getEntity().writeTo(outputStream);

    // Return result
    result = new SimpleEntry<String, ByteArrayOutputStream>(finalUrl, outputStream);
    return result;
}

From source file:com.serphacker.serposcope.scraper.http.ScrapClient.java

public int request(HttpRequestBase request) {
    synchronized (connManager) {
        try {//from  w w w  .  j  ava 2 s  . co  m
            clearPreviousRequest();
            executionTimeMS = System.currentTimeMillis();

            HttpClientContext context = HttpClientContext.create();
            initializeRequest(request, context);

            response = client.execute(request, context);
            statusCode = response.getStatusLine().getStatusCode();
            RedirectLocations redirects = context.getAttribute(HttpClientContext.REDIRECT_LOCATIONS,
                    RedirectLocations.class);
            if (redirects != null && !redirects.isEmpty()) {
                lastRedirect = redirects.get(redirects.size() - 1).toString();
            }

            HttpEntity entity = response.getEntity();
            long contentLength = entity.getContentLength();

            if (contentLength > maxResponseLength) {
                throw new ResponseTooBigException("content length (" + contentLength + ") "
                        + "is greater than max response leength (" + maxResponseLength + ")");
            }

            InputStream stream = entity.getContent();
            int totalRead = 0;
            int read = 0;

            while (totalRead < maxResponseLength
                    && (read = stream.read(buffer, totalRead, maxResponseLength - totalRead)) != -1) {
                totalRead += read;
            }

            if (totalRead == maxResponseLength && read != 0) {
                throw new ResponseTooBigException("already read " + totalRead + " bytes");
            }
            content = Arrays.copyOfRange(buffer, 0, totalRead);

        } catch (Exception ex) {
            content = null;
            statusCode = -1;
            exception = ex;
        } finally {
            proxyChangedSinceLastRequest = false;
            closeResponse();
            executionTimeMS = System.currentTimeMillis() - executionTimeMS;
        }

        return statusCode;
    }
}

From source file:com.buffalokiwi.api.API.java

/**
 * Retrieves the status and version number information from the response
 * @param response Response to pull data from
 *///from w  w w . j  av a2  s.c o m
private IAPIResponse createResponseObject(final HttpResponse response, final byte[] content,
        final String charset) {
    final RedirectLocations locations = ((RedirectLocations) context
            .getAttribute(HttpClientContext.REDIRECT_LOCATIONS));

    final List<URI> redirectLocations = new ArrayList<>();
    if (locations != null) {
        redirectLocations.addAll(locations.getAll());
    }

    return new APIResponse(response.getProtocolVersion(), response.getStatusLine(),
            new ArrayList<>(Arrays.asList(response.getAllHeaders())), redirectLocations, content, charset);
}

From source file:com.github.sardine.impl.SardineImpl.java

/**
 * Validate the response using the response handler. Aborts the request if there is an exception.
 *
 * @param <T>             Return type
 * @param request         Request to execute
 * @param responseHandler Determines the return type.
 * @return parsed response//from  w  w  w  . j  a va2 s  .co m
 */
protected <T> T execute(HttpRequestBase request, ResponseHandler<T> responseHandler) throws IOException {
    try {
        // Clear circular redirect cache
        this.context.removeAttribute(HttpClientContext.REDIRECT_LOCATIONS);
        // Execute with response handler
        return this.client.execute(request, responseHandler, this.context);
    } catch (IOException e) {
        request.abort();
        throw e;
    }
}

From source file:com.github.sardine.impl.SardineImpl.java

/**
 * No validation of the response. Aborts the request if there is an exception.
 *
 * @param request Request to execute//from ww w  .  j  a v a  2s.  co m
 * @return The response to check the reply status code
 */
protected HttpResponse execute(HttpRequestBase request) throws IOException {
    try {
        // Clear circular redirect cache
        this.context.removeAttribute(HttpClientContext.REDIRECT_LOCATIONS);
        // Execute with no response handler
        return this.client.execute(request, this.context);
    } catch (IOException e) {
        request.abort();
        throw e;
    }
}

From source file:org.apache.http.impl.client.DefaultRedirectStrategy.java

public URI getLocationURI(final HttpRequest request, final HttpResponse response, final HttpContext context)
        throws ProtocolException {
    Args.notNull(request, "HTTP request");
    Args.notNull(response, "HTTP response");
    Args.notNull(context, "HTTP context");

    final HttpClientContext clientContext = HttpClientContext.adapt(context);

    //get the location header to find out where to redirect to
    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 header");
    }//  w w w .ja  v a2  s  . c o m
    final String location = locationHeader.getValue();
    if (this.log.isDebugEnabled()) {
        this.log.debug("Redirect requested to location '" + location + "'");
    }

    final RequestConfig config = clientContext.getRequestConfig();

    URI uri = createLocationURI(location);

    // rfc2616 demands the location value be a complete URI
    // Location       = "Location" ":" absoluteURI
    try {
        if (!uri.isAbsolute()) {
            if (!config.isRelativeRedirectsAllowed()) {
                throw new ProtocolException("Relative redirect location '" + uri + "' not allowed");
            }
            // Adjust location URI
            final HttpHost target = clientContext.getTargetHost();
            Asserts.notNull(target, "Target host");
            final URI requestURI = new URI(request.getRequestLine().getUri());
            final URI absoluteRequestURI = URIUtils.rewriteURI(requestURI, target, false);
            uri = URIUtils.resolve(absoluteRequestURI, uri);
        }
    } catch (final URISyntaxException ex) {
        throw new ProtocolException(ex.getMessage(), ex);
    }

    RedirectLocations redirectLocations = (RedirectLocations) clientContext
            .getAttribute(HttpClientContext.REDIRECT_LOCATIONS);
    if (redirectLocations == null) {
        redirectLocations = new RedirectLocations();
        context.setAttribute(HttpClientContext.REDIRECT_LOCATIONS, redirectLocations);
    }
    if (!config.isCircularRedirectsAllowed()) {
        if (redirectLocations.contains(uri)) {
            throw new CircularRedirectException("Circular redirect to '" + uri + "'");
        }
    }
    redirectLocations.add(uri);
    return uri;
}