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

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

Introduction

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

Prototype

public <T> T getAttribute(String str, Class<T> cls) 

Source Link

Usage

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

public int request(HttpRequestBase request) {
    synchronized (connManager) {
        try {//from   www  .  j a  v  a2 s.  c om
            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;
    }
}