Example usage for org.apache.http.client.methods HttpUriRequest getURI

List of usage examples for org.apache.http.client.methods HttpUriRequest getURI

Introduction

In this page you can find the example usage for org.apache.http.client.methods HttpUriRequest getURI.

Prototype

URI getURI();

Source Link

Document

Returns the URI this request uses, such as <code>http://example.org/path/to/file</code>.

Usage

From source file:com.example.administrator.newsdaily.model.httpclient.AsyncHttpClient.java

/**
 * Puts a new request in queue as a new thread in pool to be executed
 *
 * @param client          HttpClient to be used for request, can differ in single requests
 * @param contentType     MIME body type, for POST and PUT requests, may be null
 * @param context         Context of Android application, to hold the reference of request
 * @param httpContext     HttpContext in which the request will be executed
 * @param responseHandler ResponseHandler or its subclass to put the response into
 * @param uriRequest      instance of HttpUriRequest, which means it must be of HttpDelete,
 *                        HttpPost, HttpGet, HttpPut, etc.
 * @return RequestHandle of future request process
 *//*from  ww  w .j  a  v  a 2  s.  com*/
protected RequestHandle sendRequest(DefaultHttpClient client, HttpContext httpContext,
        HttpUriRequest uriRequest, String contentType, ResponseHandlerInterface responseHandler,
        Context context) {
    if (uriRequest == null) {
        throw new IllegalArgumentException("HttpUriRequest must not be null");
    }

    if (responseHandler == null) {
        throw new IllegalArgumentException("ResponseHandler must not be null");
    }

    if (responseHandler.getUseSynchronousMode()) {
        throw new IllegalArgumentException(
                "Synchronous ResponseHandler used in AsyncHttpClient. You should create your response handler in a looper thread or use SyncHttpClient instead.");
    }

    if (contentType != null) {
        uriRequest.setHeader("Content-Type", contentType);
    }

    responseHandler.setRequestHeaders(uriRequest.getAllHeaders());
    responseHandler.setRequestURI(uriRequest.getURI());

    AsyncHttpRequest request = new AsyncHttpRequest(client, httpContext, uriRequest, responseHandler);
    threadPool.submit(request);
    RequestHandle requestHandle = new RequestHandle(request);

    if (context != null) {
        // Add request to request map
        List<RequestHandle> requestList = requestMap.get(context);
        if (requestList == null) {
            requestList = new LinkedList<RequestHandle>();
            requestMap.put(context, requestList);
        }

        if (responseHandler instanceof RangeFileAsyncHttpResponseHandler)
            ((RangeFileAsyncHttpResponseHandler) responseHandler).updateRequestHeaders(uriRequest);

        requestList.add(requestHandle);

        Iterator<RequestHandle> iterator = requestList.iterator();
        while (iterator.hasNext()) {
            if (iterator.next().shouldBeGarbageCollected()) {
                iterator.remove();
            }
        }
    }

    return requestHandle;
}

From source file:com.activiti.service.activiti.ActivitiClientService.java

/**
 * Execute the given request. Will return the parsed JSON present in the response-body, in case the status code is as expected.
 * In case the response returns a different status-code, an {@link ActivitiServiceException} is thrown with the error message received
 * from the client, if possible./*from www.j  a v  a  2 s  . c  o  m*/
 */
public JsonNode executeRequest(HttpUriRequest request, String userName, String password,
        int expectedStatusCode) {

    ActivitiServiceException exception = null;
    CloseableHttpClient client = getHttpClient(userName, password);
    try {
        CloseableHttpResponse response = client.execute(request);

        try {
            InputStream responseContent = response.getEntity().getContent();
            String strResponse = IOUtils.toString(responseContent);

            boolean success = response.getStatusLine() != null
                    && response.getStatusLine().getStatusCode() == expectedStatusCode;
            if (success) {
                JsonNode bodyNode = objectMapper.readTree(strResponse);
                return bodyNode;

            } else {
                JsonNode bodyNode = null;
                try {
                    bodyNode = objectMapper.readTree(strResponse);
                } catch (Exception e) {
                    log.debug("Error parsing error message", e);
                }
                exception = new ActivitiServiceException(extractError(bodyNode,
                        "An error occured while calling Activiti: " + response.getStatusLine()));
            }
        } catch (Exception e) {
            log.warn("Error consuming response from uri " + request.getURI(), e);
            exception = wrapException(e, request);
        } finally {
            response.close();
        }

    } catch (Exception e) {
        log.error("Error executing request to uri " + request.getURI(), e);
        exception = wrapException(e, request);
    } finally {
        try {
            client.close();
        } catch (Exception e) {
            log.warn("Error closing http client instance", e);
        }
    }

    if (exception != null) {
        throw exception;
    }

    return null;
}

From source file:com.tandong.sa.aq.AbstractAjaxCallback.java

private void httpDo(HttpUriRequest hr, String url, Map<String, String> headers, AjaxStatus status)
        throws ClientProtocolException, IOException {

    if (AGENT != null) {
        hr.addHeader("User-Agent", AGENT);
    }/*from w  w w  . j  a  va2  s  . co m*/

    if (headers != null) {
        for (String name : headers.keySet()) {
            hr.addHeader(name, headers.get(name));
        }

    }

    if (GZIP && (headers == null || !headers.containsKey("Accept-Encoding"))) {
        hr.addHeader("Accept-Encoding", "gzip");
    }

    String cookie = makeCookie();
    if (cookie != null) {
        hr.addHeader("Cookie", cookie);
    }

    if (ah != null) {
        ah.applyToken(this, hr);
    }

    DefaultHttpClient client = getClient();

    HttpParams hp = hr.getParams();
    if (proxy != null)
        hp.setParameter(ConnRoutePNames.DEFAULT_PROXY, proxy);
    if (timeout > 0) {
        AQUtility.debug("timeout param", CoreConnectionPNames.CONNECTION_TIMEOUT);
        hp.setParameter(CoreConnectionPNames.CONNECTION_TIMEOUT, timeout);
        hp.setParameter(CoreConnectionPNames.SO_TIMEOUT, timeout);
    }

    HttpContext context = new BasicHttpContext();
    CookieStore cookieStore = new BasicCookieStore();
    context.setAttribute(ClientContext.COOKIE_STORE, cookieStore);

    request = hr;

    if (abort) {
        throw new IOException("Aborted");
    }

    HttpResponse response = client.execute(hr, context);

    byte[] data = null;

    String redirect = url;

    int code = response.getStatusLine().getStatusCode();
    String message = response.getStatusLine().getReasonPhrase();
    String error = null;

    HttpEntity entity = response.getEntity();

    Header[] hs = response.getAllHeaders();
    HashMap<String, String> responseHeaders = new HashMap<String, String>(hs.length);
    for (Header h : hs) {
        responseHeaders.put(h.getName(), h.getValue());
    }
    setResponseHeaders(responseHeaders);

    File file = null;

    if (code < 200 || code >= 300) {

        try {

            if (entity != null) {

                InputStream is = entity.getContent();
                byte[] s = toData(getEncoding(entity), is);

                error = new String(s, "UTF-8");

                AQUtility.debug("error", error);

            }
        } catch (Exception e) {
            AQUtility.debug(e);
        }

    } else {

        HttpHost currentHost = (HttpHost) context.getAttribute(ExecutionContext.HTTP_TARGET_HOST);
        HttpUriRequest currentReq = (HttpUriRequest) context.getAttribute(ExecutionContext.HTTP_REQUEST);
        redirect = currentHost.toURI() + currentReq.getURI();

        int size = Math.max(32, Math.min(1024 * 64, (int) entity.getContentLength()));

        OutputStream os = null;
        InputStream is = null;

        try {
            file = getPreFile();

            if (file == null) {
                os = new PredefinedBAOS(size);
            } else {
                file.createNewFile();
                os = new BufferedOutputStream(new FileOutputStream(file));
            }

            //AQUtility.time("copy");

            copy(entity.getContent(), os, getEncoding(entity), (int) entity.getContentLength());

            //AQUtility.timeEnd("copy", 0);

            os.flush();

            if (file == null) {
                data = ((PredefinedBAOS) os).toByteArray();
            } else {
                if (!file.exists() || file.length() == 0) {
                    file = null;
                }
            }

        } finally {
            AQUtility.close(is);
            AQUtility.close(os);
        }

    }

    AQUtility.debug("response", code);
    if (data != null) {
        AQUtility.debug(data.length, url);
    }

    status.code(code).message(message).error(error).redirect(redirect).time(new Date()).data(data).file(file)
            .client(client).context(context).headers(response.getAllHeaders());

}

From source file:com.androidquery.callback.AbstractAjaxCallback.java

private void httpDo(HttpUriRequest hr, String url, Map<String, String> headers, AjaxStatus status)
        throws ClientProtocolException, IOException {

    if (AGENT != null) {
        hr.addHeader("User-Agent", AGENT);
    }/*from w ww  .  j av a 2s .co  m*/

    if (headers != null) {
        for (String name : headers.keySet()) {
            hr.addHeader(name, headers.get(name));
        }

    }

    if (GZIP && (headers == null || !headers.containsKey("Accept-Encoding"))) {
        hr.addHeader("Accept-Encoding", "gzip");
    }

    String cookie = makeCookie();
    if (cookie != null) {
        hr.addHeader("Cookie", cookie);
    }

    if (ah != null) {
        ah.applyToken(this, hr);
    }

    DefaultHttpClient client = getClient();

    HttpParams hp = hr.getParams();
    if (proxy != null)
        hp.setParameter(ConnRoutePNames.DEFAULT_PROXY, proxy);
    if (timeout > 0) {
        hp.setParameter(CoreConnectionPNames.CONNECTION_TIMEOUT, timeout);
        hp.setParameter(CoreConnectionPNames.SO_TIMEOUT, timeout);
    }

    HttpContext context = new BasicHttpContext();
    CookieStore cookieStore = new BasicCookieStore();
    context.setAttribute(ClientContext.COOKIE_STORE, cookieStore);

    request = hr;

    if (abort) {
        throw new IOException("Aborted");
    }

    HttpResponse response = null;

    try {
        response = client.execute(hr, context);
    } catch (HttpHostConnectException e) {

        //if proxy is used, automatically retry without proxy
        if (proxy != null) {
            AQUtility.debug("proxy failed, retrying without proxy");
            hp.setParameter(ConnRoutePNames.DEFAULT_PROXY, null);
            response = client.execute(hr, context);
        } else {
            throw e;
        }
    }

    byte[] data = null;

    String redirect = url;

    int code = response.getStatusLine().getStatusCode();
    String message = response.getStatusLine().getReasonPhrase();
    String error = null;

    HttpEntity entity = response.getEntity();

    File file = null;

    if (code < 200 || code >= 300) {

        InputStream is = null;

        try {

            if (entity != null) {

                is = entity.getContent();
                byte[] s = toData(getEncoding(entity), is);

                error = new String(s, "UTF-8");

                AQUtility.debug("error", error);

            }
        } catch (Exception e) {
            AQUtility.debug(e);
        } finally {
            AQUtility.close(is);
        }

    } else {

        HttpHost currentHost = (HttpHost) context.getAttribute(ExecutionContext.HTTP_TARGET_HOST);
        HttpUriRequest currentReq = (HttpUriRequest) context.getAttribute(ExecutionContext.HTTP_REQUEST);
        redirect = currentHost.toURI() + currentReq.getURI();

        int size = Math.max(32, Math.min(1024 * 64, (int) entity.getContentLength()));

        OutputStream os = null;
        InputStream is = null;

        try {
            file = getPreFile();

            if (file == null) {
                os = new PredefinedBAOS(size);
            } else {
                file.createNewFile();
                os = new BufferedOutputStream(new FileOutputStream(file));
            }

            //AQUtility.time("copy");

            copy(entity.getContent(), os, getEncoding(entity), (int) entity.getContentLength());

            //AQUtility.timeEnd("copy", 0);

            os.flush();

            if (file == null) {
                data = ((PredefinedBAOS) os).toByteArray();
            } else {
                if (!file.exists() || file.length() == 0) {
                    file = null;
                }
            }

        } finally {
            AQUtility.close(is);
            AQUtility.close(os);
        }

    }

    AQUtility.debug("response", code);
    if (data != null) {
        AQUtility.debug(data.length, url);
    }

    status.code(code).message(message).error(error).redirect(redirect).time(new Date()).data(data).file(file)
            .client(client).context(context).headers(response.getAllHeaders());

}

From source file:com.rae.core.http.async.AsyncHttpClient.java

/**
 * Puts a new request in queue as a new thread in pool to be executed
 *
 * @param client          HttpClient to be used for request, can differ in single requests
 * @param contentType     MIME body type, for POST and PUT requests, may be null
 * @param context         Context of Android application, to hold the reference of request
 * @param httpContext     HttpContext in which the request will be executed
 * @param responseHandler ResponseHandler or its subclass to put the response into
 * @param uriRequest      instance of HttpUriRequest, which means it must be of HttpDelete,
 *                        HttpPost, HttpGet, HttpPut, etc.
 * @return RequestHandle of future request process
 *///from www .  j  ava 2 s .c om
protected RequestHandle sendRequest(DefaultHttpClient client, HttpContext httpContext,
        HttpUriRequest uriRequest, String contentType, ResponseHandlerInterface responseHandler,
        Context context) {
    if (uriRequest == null) {
        throw new IllegalArgumentException("HttpUriRequest must not be null");
    }

    if (responseHandler == null) {
        throw new IllegalArgumentException("ResponseHandler must not be null");
    }

    if (responseHandler.getUseSynchronousMode()) {
        throw new IllegalArgumentException(
                "Synchronous ResponseHandler used in AsyncHttpClient. You should create your response handler in a looper thread or use SyncHttpClient instead.");
    }

    if (contentType != null) {
        uriRequest.setHeader("Content-Type", contentType);
    }

    responseHandler.setRequestHeaders(uriRequest.getAllHeaders());
    responseHandler.setRequestURI(uriRequest.getURI());

    AsyncHttpRequest request = newAsyncHttpRequest(client, httpContext, uriRequest, contentType,
            responseHandler, context);
    threadPool.submit(request);
    RequestHandle requestHandle = new RequestHandle(request);

    if (context != null) {
        // Add request to request map
        List<RequestHandle> requestList = requestMap.get(context);
        if (requestList == null) {
            requestList = new LinkedList<RequestHandle>();
            requestMap.put(context, requestList);
        }

        if (responseHandler instanceof RangeFileAsyncHttpResponseHandler)
            ((RangeFileAsyncHttpResponseHandler) responseHandler).updateRequestHeaders(uriRequest);

        requestList.add(requestHandle);

        Iterator<RequestHandle> iterator = requestList.iterator();
        while (iterator.hasNext()) {
            if (iterator.next().shouldBeGarbageCollected()) {
                iterator.remove();
            }
        }
    }

    return requestHandle;
}

From source file:com.appbase.androidquery.callback.AbstractAjaxCallback.java

private HttpResponse execute(HttpUriRequest hr, DefaultHttpClient client, HttpContext context)
        throws ClientProtocolException, IOException {

    HttpResponse response = null;/*from  w ww .  j  ava  2 s.c o m*/

    if (hr.getURI().getAuthority().contains("_")) {
        URL urlObj = hr.getURI().toURL();
        HttpHost host;
        if (urlObj.getPort() == -1) {
            host = new HttpHost(urlObj.getHost(), 80, urlObj.getProtocol());
        } else {
            host = new HttpHost(urlObj.getHost(), urlObj.getPort(), urlObj.getProtocol());
        }
        response = client.execute(host, hr, context);
    } else {
        response = client.execute(hr, context);
    }

    return response;
}

From source file:org.openrdf.http.client.SparqlSession.java

/**
 * Parse the response in this thread using the provided {@link RDFHandler}.
 * All HTTP connections are closed and released in this method
 *///from   w w  w.j a v a 2s .  co  m
protected void getRDF(HttpUriRequest method, RDFHandler handler, boolean requireContext)
        throws IOException, RDFHandlerException, RepositoryException, MalformedQueryException,
        UnauthorizedException, QueryInterruptedException {
    // Specify which formats we support using Accept headers
    Set<RDFFormat> rdfFormats = RDFParserRegistry.getInstance().getKeys();
    if (rdfFormats.isEmpty()) {
        throw new RepositoryException("No tuple RDF parsers have been registered");
    }

    // send the tuple query
    HttpResponse response = sendGraphQueryViaHttp(method, requireContext, rdfFormats);
    try {

        String mimeType = getResponseMIMEType(response);
        try {
            RDFFormat format = RDFFormat.matchMIMEType(mimeType, rdfFormats);
            RDFParser parser = Rio.createParser(format, getValueFactory());
            parser.setParserConfig(getParserConfig());
            parser.setParseErrorListener(new ParseErrorLogger());
            parser.setRDFHandler(handler);
            parser.parse(response.getEntity().getContent(), method.getURI().toASCIIString());
        } catch (UnsupportedRDFormatException e) {
            throw new RepositoryException("Server responded with an unsupported file format: " + mimeType);
        } catch (RDFParseException e) {
            throw new RepositoryException("Malformed query result from server", e);
        }
    } finally {
        EntityUtils.consumeQuietly(response.getEntity());
    }
}

From source file:com.activiti.service.activiti.ActivitiClientService.java

public JsonNode executeDownloadRequest(HttpUriRequest request, HttpServletResponse httpResponse,
        String userName, String password, int expectedStatusCode) {

    ActivitiServiceException exception = null;
    CloseableHttpClient client = getHttpClient(userName, password);
    try {// ww  w  . j av  a  2s. c o  m
        CloseableHttpResponse response = client.execute(request);
        try {
            boolean success = response.getStatusLine() != null
                    && response.getStatusLine().getStatusCode() == expectedStatusCode;
            if (success) {
                httpResponse.setHeader("Content-Disposition",
                        response.getHeaders("Content-Disposition")[0].getValue());
                response.getEntity().writeTo(httpResponse.getOutputStream());
                return null;

            } else {
                JsonNode bodyNode = null;
                String strResponse = IOUtils.toString(response.getEntity().getContent());
                try {
                    bodyNode = objectMapper.readTree(strResponse);
                } catch (Exception e) {
                    log.debug("Error parsing error message", e);
                }
                exception = new ActivitiServiceException(extractError(bodyNode,
                        "An error occured while calling Activiti: " + response.getStatusLine()));
            }
        } catch (Exception e) {
            log.warn("Error consuming response from uri " + request.getURI(), e);
            exception = wrapException(e, request);
        } finally {
            response.close();
        }

    } catch (Exception e) {
        log.error("Error executing request to uri " + request.getURI(), e);
        exception = wrapException(e, request);
    } finally {
        try {
            client.close();
        } catch (Exception e) {
            log.warn("Error closing http client instance", e);
        }
    }

    if (exception != null) {
        throw exception;
    }

    return null;
}

From source file:com.joyent.manta.http.EncryptionHttpHelper.java

/**
 * Calculates the skip bytes and plaintext length for a encrypted ranged
 * request./*from ww  w .  j a v  a  2 s  . c  o m*/
 *
 * @param request source request that hasn't been made yet
 * @param requestHeaders headers passed to the request
 * @return a {@link Long} array containing two elements: skip bytes, plaintext length
 * @throws IOException thrown when we fail making an additional HEAD request
 */
private PlaintextByteRangePosition calculateSkipBytesAndPlaintextLength(final HttpUriRequest request,
        final MantaHttpHeaders requestHeaders) throws IOException {
    final Long initialSkipBytes;
    Long plaintextRangeLength = 0L;

    final long[] plaintextRanges = byteRangeAsNullSafe(requestHeaders.getByteRange(), this.cipherDetails);

    final long plaintextStart = plaintextRanges[0];
    final long plaintextEnd = plaintextRanges[1];

    final long binaryStartPositionInclusive;
    final long binaryEndPositionInclusive;

    final boolean negativeEndRequest = plaintextEnd < 0;

    // We have been passed a request in the form of something like: bytes=-50
    if (plaintextStart == 0 && negativeEndRequest) {
        /* Since we don't know the size of the object, there is no way
         * for us to know what the value of objectSize - N is. So we
         * do a HEAD request and discover the plaintext object size
         * and the size of the ciphertext. This allows us to have
         * the information needed to do a proper range request. */
        final String path = request.getURI().getPath();

        // Forward on all headers to the HEAD request
        final HttpHead head = getRequestFactory().head(path);
        MantaHttpRequestFactory.addHeaders(head, request.getAllHeaders());
        head.removeHeaders(HttpHeaders.RANGE);

        HttpResponse headResponse = super.executeAndCloseRequest(head, "HEAD   {} response [{}] {} ");
        final MantaHttpHeaders headers = new MantaHttpHeaders(headResponse.getAllHeaders());
        MantaObjectResponse objectResponse = new MantaObjectResponse(path, headers);

        /* We make the actual GET request's success dependent on the
         * object not changing since we did the HEAD request. */
        request.setHeader(HttpHeaders.IF_MATCH, objectResponse.getEtag());
        request.setHeader(HttpHeaders.IF_UNMODIFIED_SINCE,
                objectResponse.getHeaderAsString(HttpHeaders.LAST_MODIFIED));

        Long ciphertextSize = objectResponse.getContentLength();
        Validate.notNull(ciphertextSize, "Manta should always return a content-size");

        // We query the response object for multiple properties that will
        // give us the plaintext size. If not possible, this will error.
        long fullPlaintextSize = HttpHelper.attemptToFindPlaintextSize(objectResponse, ciphertextSize,
                this.cipherDetails);

        // Since plaintextEnd is a negative value - this will be set to
        // the number of bytes before the end of the file (in plaintext)
        initialSkipBytes = plaintextEnd + fullPlaintextSize;

        // calculates the ciphertext byte range
        final ByteRangeConversion computedRanges = this.cipherDetails.translateByteRange(initialSkipBytes,
                fullPlaintextSize - 1);

        // We only use the ciphertext start position, because we already
        // have the position of the end of the ciphertext (eg content-length)
        binaryStartPositionInclusive = computedRanges.getCiphertextStartPositionInclusive();
        binaryEndPositionInclusive = ciphertextSize;
        // This is the typical case like: bytes=3-44
    } else {

        long scaledPlaintextEnd = plaintextEnd;

        // interpret maximum plaintext value as unbounded end
        if (plaintextEnd == cipherDetails.getMaximumPlaintextSizeInBytes()) {

            scaledPlaintextEnd--;
        }

        // calculates the ciphertext byte range
        final ByteRangeConversion computedRanges = this.cipherDetails.translateByteRange(plaintextStart,
                scaledPlaintextEnd);

        binaryStartPositionInclusive = computedRanges.getCiphertextStartPositionInclusive();
        initialSkipBytes = computedRanges.getPlaintextBytesToSkipInitially()
                + computedRanges.getCiphertextStartPositionInclusive();

        if (computedRanges.getCiphertextEndPositionInclusive() > 0) {
            binaryEndPositionInclusive = computedRanges.getCiphertextEndPositionInclusive();
        } else {
            binaryEndPositionInclusive = 0;
        }

        plaintextRangeLength = (scaledPlaintextEnd - plaintextStart) + 1;
    }

    // We don't know the ending position
    if (binaryEndPositionInclusive == 0) {
        requestHeaders.setRange(String.format("bytes=%d-", binaryStartPositionInclusive));
    } else {
        requestHeaders.setRange(
                String.format("bytes=%d-%d", binaryStartPositionInclusive, binaryEndPositionInclusive));
    }

    // Range in the form of 50-, so we don't know the actual plaintext length
    if (plaintextEnd >= cipherDetails.getMaximumPlaintextSizeInBytes()) {
        plaintextRangeLength = 0L;
    }

    return new PlaintextByteRangePosition().setInitialPlaintextSkipBytes(initialSkipBytes)
            .setPlaintextRangeLength(plaintextRangeLength).setPlaintextStart(plaintextStart)
            .setPlaintextEnd(plaintextEnd);
}

From source file:net.oddsoftware.android.feedscribe.data.FeedManager.java

void downloadFeedHttp(Feed feed, FeedStatus feedStatus, ArrayList<FeedItem> feedItems,
        ArrayList<Enclosure> enclosures) {
    try {/*from w w w. java 2s.c  o  m*/
        // use apache http client lib to set parameters from feedStatus
        DefaultHttpClient client = new DefaultHttpClient();

        // set up proxy handler
        ProxySelectorRoutePlanner routePlanner = new ProxySelectorRoutePlanner(
                client.getConnectionManager().getSchemeRegistry(), ProxySelector.getDefault());
        client.setRoutePlanner(routePlanner);

        HttpGet request = new HttpGet(feed.mURL);

        HttpContext httpContext = new BasicHttpContext();

        request.setHeader("User-Agent", USER_AGENT);

        // send etag if we have it
        if (feedStatus.mETag.length() > 0) {
            request.setHeader("If-None-Match", feedStatus.mETag);
        }

        // send If-Modified-Since if we have it
        if (feedStatus.mLastModified.getTime() > 0) {
            SimpleDateFormat dateFormat = new SimpleDateFormat("EEE', 'dd' 'MMM' 'yyyy' 'HH:mm:ss' GMT'",
                    Locale.US);
            dateFormat.setTimeZone(TimeZone.getTimeZone("GMT"));
            String formattedTime = dateFormat.format(feedStatus.mLastModified);
            // If-Modified-Since: Sat, 29 Oct 1994 19:43:31 GMT
            request.setHeader("If-Modified-Since", formattedTime);
        }

        request.setHeader("Accept-Encoding", "gzip,deflate");
        HttpResponse response = client.execute(request, httpContext);

        if (mLog.d())
            mLog.d("http request: " + feed.mURL);
        if (mLog.d())
            mLog.d("http response code: " + response.getStatusLine());

        InputStream inputStream = null;

        StatusLine status = response.getStatusLine();
        HttpEntity entity = response.getEntity();

        if (entity != null) {
            inputStream = entity.getContent();
        }

        try {
            if (entity != null && status.getStatusCode() == 200) {
                Header encodingHeader = entity.getContentEncoding();

                if (encodingHeader != null) {
                    if (encodingHeader.getValue().equalsIgnoreCase("gzip")) {
                        inputStream = new GZIPInputStream(inputStream);
                    } else if (encodingHeader.getValue().equalsIgnoreCase("deflate")) {
                        inputStream = new InflaterInputStream(inputStream);
                    }
                }

                // remove caching attributes to be replaced with new ones
                feedStatus.mETag = "";
                feedStatus.mLastModified.setTime(0);
                feedStatus.mTTL = 0;

                boolean success = parseFeed(inputStream, feed, feedStatus, feedItems, enclosures);

                if (success) {
                    // if the parse was ok, update these attributes
                    // ETag: "6050003-78e5-4981d775e87c0"
                    Header etagHeader = response.getFirstHeader("ETag");
                    if (etagHeader != null) {
                        if (etagHeader.getValue().length() < MAX_ETAG_LENGTH) {
                            feedStatus.mETag = etagHeader.getValue();
                        } else {
                            mLog.e("etag length was too big: " + etagHeader.getValue().length());
                        }
                    }

                    // Last-Modified: Fri, 24 Dec 2010 00:57:11 GMT
                    Header lastModifiedHeader = response.getFirstHeader("Last-Modified");
                    if (lastModifiedHeader != null) {
                        try {
                            feedStatus.mLastModified = parseRFC822Date(lastModifiedHeader.getValue());
                        } catch (ParseException exc) {
                            mLog.e("unable to parse date", exc);
                        }
                    }

                    HttpUriRequest currentReq = (HttpUriRequest) httpContext
                            .getAttribute(ExecutionContext.HTTP_REQUEST);
                    HttpHost currentHost = (HttpHost) httpContext
                            .getAttribute(ExecutionContext.HTTP_TARGET_HOST);
                    String currentUrl = currentHost.toURI() + currentReq.getURI();

                    mLog.w("loaded redirect from " + request.getURI().toString() + " to " + currentUrl);

                    feedStatus.mLastURL = currentUrl;
                }
            } else {
                if (status.getStatusCode() == 304) {
                    mLog.d("received 304 not modified");
                }
            }
        } finally {
            if (inputStream != null) {
                inputStream.close();
            }
        }
    } catch (IOException exc) {
        mLog.e("error downloading feed " + feed.mURL, exc);
    }
}