Example usage for org.apache.http.protocol HttpContext getAttribute

List of usage examples for org.apache.http.protocol HttpContext getAttribute

Introduction

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

Prototype

Object getAttribute(String str);

Source Link

Usage

From source file:com.appbase.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  w w.  j a  v a 2s  .c o 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);
        response = execute(hr, client, 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);
            response = execute(hr, client, 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));
            }

            is = entity.getContent();
            if ("gzip".equalsIgnoreCase(getEncoding(entity))) {
                is = new GZIPInputStream(is);
            }

            copy(is, os, (int) entity.getContentLength());

            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.amytech.android.library.utils.asynchttp.AsyncHttpClient.java

/**
 * Creates a new AsyncHttpClient.//from w  ww  . j  a  va 2  s . c om
 *
 * @param schemeRegistry
 *            SchemeRegistry to be used
 */
public AsyncHttpClient(SchemeRegistry schemeRegistry) {

    BasicHttpParams httpParams = new BasicHttpParams();

    ConnManagerParams.setTimeout(httpParams, connectTimeout);
    ConnManagerParams.setMaxConnectionsPerRoute(httpParams, new ConnPerRouteBean(maxConnections));
    ConnManagerParams.setMaxTotalConnections(httpParams, DEFAULT_MAX_CONNECTIONS);

    HttpConnectionParams.setSoTimeout(httpParams, responseTimeout);
    HttpConnectionParams.setConnectionTimeout(httpParams, connectTimeout);
    HttpConnectionParams.setTcpNoDelay(httpParams, true);
    HttpConnectionParams.setSocketBufferSize(httpParams, DEFAULT_SOCKET_BUFFER_SIZE);

    HttpProtocolParams.setVersion(httpParams, HttpVersion.HTTP_1_1);

    ClientConnectionManager cm = createConnectionManager(schemeRegistry, httpParams);
    Utils.asserts(cm != null,
            "Custom implementation of #createConnectionManager(SchemeRegistry, BasicHttpParams) returned null");

    threadPool = getDefaultThreadPool();
    requestMap = Collections.synchronizedMap(new WeakHashMap<Context, List<RequestHandle>>());
    clientHeaderMap = new HashMap<String, String>();

    httpContext = new SyncBasicHttpContext(new BasicHttpContext());
    httpClient = new DefaultHttpClient(cm, httpParams);
    httpClient.addRequestInterceptor(new HttpRequestInterceptor() {
        @Override
        public void process(HttpRequest request, HttpContext context) {
            if (!request.containsHeader(HEADER_ACCEPT_ENCODING)) {
                request.addHeader(HEADER_ACCEPT_ENCODING, ENCODING_GZIP);
            }
            for (String header : clientHeaderMap.keySet()) {
                if (request.containsHeader(header)) {
                    Header overwritten = request.getFirstHeader(header);
                    Log.d(LOG_TAG,
                            String.format("Headers were overwritten! (%s | %s) overwrites (%s | %s)", header,
                                    clientHeaderMap.get(header), overwritten.getName(),
                                    overwritten.getValue()));

                    // remove the overwritten header
                    request.removeHeader(overwritten);
                }
                request.addHeader(header, clientHeaderMap.get(header));
            }
        }
    });

    httpClient.addResponseInterceptor(new HttpResponseInterceptor() {
        @Override
        public void process(HttpResponse response, HttpContext context) {
            final HttpEntity entity = response.getEntity();
            if (entity == null) {
                return;
            }
            final Header encoding = entity.getContentEncoding();
            if (encoding != null) {
                for (HeaderElement element : encoding.getElements()) {
                    if (element.getName().equalsIgnoreCase(ENCODING_GZIP)) {
                        response.setEntity(new InflatingEntity(entity));
                        break;
                    }
                }
            }
        }
    });

    httpClient.addRequestInterceptor(new HttpRequestInterceptor() {
        @Override
        public void process(final HttpRequest request, final HttpContext context)
                throws HttpException, IOException {
            AuthState authState = (AuthState) context.getAttribute(ClientContext.TARGET_AUTH_STATE);
            CredentialsProvider credsProvider = (CredentialsProvider) context
                    .getAttribute(ClientContext.CREDS_PROVIDER);
            HttpHost targetHost = (HttpHost) context.getAttribute(ExecutionContext.HTTP_TARGET_HOST);

            if (authState.getAuthScheme() == null) {
                AuthScope authScope = new AuthScope(targetHost.getHostName(), targetHost.getPort());
                Credentials creds = credsProvider.getCredentials(authScope);
                if (creds != null) {
                    authState.setAuthScheme(new BasicScheme());
                    authState.setCredentials(creds);
                }
            }
        }
    }, 0);

    httpClient
            .setHttpRequestRetryHandler(new RetryHandler(DEFAULT_MAX_RETRIES, DEFAULT_RETRY_SLEEP_TIME_MILLIS));
}

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  ww .j  av a 2  s  .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);
    }
}

From source file:net.oddsoftware.android.html.HttpCache.java

private void download(CacheItem cacheItem) {
    try {/*w ww.ja  v  a  2  s.  co m*/
        // check to see if file exist, if so check etag and last-modified
        if (cacheItem.mFilename.length() > 0) {
            File f = new File(cacheItem.mFilename);

            try {
                InputStream is = new FileInputStream(f);
                is.close();
            } catch (IOException exc) {
                // no file, nuke the cache stats
                cacheItem.mETag = "";
                cacheItem.mLastModified = 0;
            }
        } else {
            cacheItem.mFilename = mCacheDirectory + File.separator + UUID.randomUUID().toString() + ".html.gz";
        }

        HttpContext httpContext = new BasicHttpContext();
        HttpClient client = createHttpClient();
        HttpUriRequest request = createHttpRequest(cacheItem.mUrl, cacheItem.mETag, cacheItem.mLastModified);

        if (request == null || request.getURI() == null || request.getURI().getHost() == null
                || request.getURI().getHost().length() == 0) {
            if (Globals.LOGGING)
                Log.e(Globals.LOG_TAG, "unable to create http request for url " + cacheItem.mUrl);
            return; // sadness
        }

        HttpResponse response = client.execute(request, httpContext);

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

        if (status.getStatusCode() == 304) {
            if (Globals.LOGGING)
                Log.d(Globals.LOG_TAG, "received 304 not modified");

            cacheItem.mHitTime = new Date().getTime();

            cacheItem.update(mContentResolver);

            return;
        }

        if (status.getStatusCode() == 200) {
            InputStream inputStream = null;

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

            long contentLength = entity.getContentLength();

            if (contentLength > MAX_CONTENT_LENGTH) {
                if (Globals.LOGGING)
                    Log.w(Globals.LOG_TAG, "HttpCache.download item " + cacheItem.mUrl
                            + " content length is too big " + contentLength);
                return;
            }

            Header encodingHeader = entity.getContentEncoding();
            boolean encoded = false;

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

            File tmpFile = File.createTempFile("httpcache", ".html.gz.tmp", mCacheDirectory);
            OutputStream os = new GZIPOutputStream(new FileOutputStream(tmpFile));

            byte[] buffer = new byte[4096];
            int count = 0;
            long fileSize = 0;
            while ((count = inputStream.read(buffer)) != -1) {
                os.write(buffer, 0, count);
                fileSize += count;
            }
            inputStream.close();
            os.close();

            if (!encoded && contentLength > 0 && fileSize != contentLength) {
                Log.e(Globals.LOG_TAG, "HttpCache.download: content-length: " + contentLength
                        + " but file size: " + fileSize + " aborting");
                tmpFile.delete();
                return;
            }

            tmpFile.renameTo(new File(cacheItem.mFilename));

            // 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) {
                    cacheItem.mETag = etagHeader.getValue();
                } else {
                    if (Globals.LOGGING)
                        Log.e(Globals.LOG_TAG, "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 {
                    cacheItem.mLastModified = FeedManager.parseRFC822Date(lastModifiedHeader.getValue())
                            .getTime();
                } catch (ParseException exc) {
                    if (Globals.LOGGING)
                        Log.e(Globals.LOG_TAG, "unable to parse date", exc);
                }
            }

            // Expires: Thu, 01 Dec 1994 16:00:00 GMT
            Header expiresHeader = response.getFirstHeader("Expires");
            if (expiresHeader != null) {
                try {
                    cacheItem.mExpiresAt = FeedManager.parseRFC822Date(expiresHeader.getValue()).getTime();
                } catch (ParseException exc) {
                    if (Globals.LOGGING)
                        Log.e(Globals.LOG_TAG, "unable to parse expires", exc);
                }
            }

            long now = new Date().getTime() + DEFAULT_EXPIRES;
            if (cacheItem.mExpiresAt < now) {
                cacheItem.mExpiresAt = now;
            }

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

            if (Globals.LOGGING)
                Log.w(Globals.LOG_TAG,
                        "loaded redirect from " + request.getURI().toString() + " to " + currentUrl);

            cacheItem.mLastUrl = currentUrl;

            cacheItem.mHitTime = new Date().getTime();

            cacheItem.update(mContentResolver);
        }
    } catch (IOException exc) {
        if (Globals.LOGGING) {
            Log.e(Globals.LOG_TAG, "error downloading file to cache", exc);
        }
    }
}

From source file:org.apache.axis2.transport.nhttp.ClientHandler.java

/**
 * Process ready input (i.e. response from remote server)
 * @param conn connection being processed
 * @param decoder the content decoder in use
 *//*from  w  w  w. j  a  va2  s  .  c o  m*/
public void inputReady(final NHttpClientConnection conn, final ContentDecoder decoder) {
    HttpContext context = conn.getContext();
    HttpResponse response = conn.getHttpResponse();
    Pipe.SinkChannel sink = (Pipe.SinkChannel) context.getAttribute(RESPONSE_SINK_CHANNEL);
    ByteBuffer inbuf = (ByteBuffer) context.getAttribute(REQUEST_BUFFER);

    try {
        while (decoder.read(inbuf) > 0) {
            inbuf.flip();
            sink.write(inbuf);
            inbuf.compact();
        }

        if (decoder.isCompleted()) {
            sink.close();
            if (!connStrategy.keepAlive(response, context)) {
                conn.close();
            } else {
                ConnectionPool.release(conn);
            }
        }

    } catch (IOException e) {
        handleException("I/O Error : " + e.getMessage(), e, conn);
    }
}

From source file:org.apache.axis2.transport.nhttp.ClientHandler.java

/**
 * Process ready output (i.e. write request to remote server)
 * @param conn the connection being processed
 * @param encoder the encoder in use/*from   ww  w  .j  av a 2 s .co  m*/
 */
public void outputReady(final NHttpClientConnection conn, final ContentEncoder encoder) {
    HttpContext context = conn.getContext();
    HttpResponse response = conn.getHttpResponse();

    Pipe.SourceChannel source = (Pipe.SourceChannel) context.getAttribute(REQUEST_SOURCE_CHANNEL);
    ByteBuffer outbuf = (ByteBuffer) context.getAttribute(RESPONSE_BUFFER);

    try {
        int bytesRead = source.read(outbuf);
        if (bytesRead == -1) {
            encoder.complete();
        } else {
            outbuf.flip();
            encoder.write(outbuf);
            outbuf.compact();
        }

        if (encoder.isCompleted()) {
            source.close();
        }

    } catch (IOException e) {
        handleException("I/O Error : " + e.getMessage(), e, conn);
    }
}

From source file:org.apache.axis2.transport.nhttp.ClientHandler.java

/**
 * Process a response received for the request sent out
 * @param conn the connection being processed
 *//*from   www.j  a  va2  s. c o  m*/
public void responseReceived(final NHttpClientConnection conn) {
    HttpContext context = conn.getContext();
    HttpResponse response = conn.getHttpResponse();

    try {
        Pipe responsePipe = Pipe.open();
        context.setAttribute(RESPONSE_SINK_CHANNEL, responsePipe.sink());

        BasicHttpEntity entity = new BasicHttpEntity();
        if (response.getStatusLine().getHttpVersion().greaterEquals(HttpVersion.HTTP_1_1)) {
            entity.setChunked(true);
        }
        response.setEntity(entity);
        context.setAttribute(HttpContext.HTTP_RESPONSE, response);

        workerPool.execute(new ClientWorker(cfgCtx, Channels.newInputStream(responsePipe.source()),
                (MessageContext) context.getAttribute(OUTGOING_MESSAGE_CONTEXT)));

    } catch (IOException e) {
        handleException("I/O Error : " + e.getMessage(), e, conn);
    }
}

From source file:org.apache.axis2.transport.nhttp.ServerHandler.java

/**
 * Process ready input by writing it into the Pipe
 * @param conn the connection being processed
 * @param decoder the content decoder in use
 *//*from w  w  w. j  ava  2 s.  com*/
public void inputReady(final NHttpServerConnection conn, final ContentDecoder decoder) {

    HttpContext context = conn.getContext();
    Pipe.SinkChannel sink = (Pipe.SinkChannel) context.getAttribute(REQUEST_SINK_CHANNEL);
    ByteBuffer inbuf = (ByteBuffer) context.getAttribute(REQUEST_BUFFER);

    try {
        while (decoder.read(inbuf) > 0) {
            inbuf.flip();
            sink.write(inbuf);
            inbuf.compact();
        }

        if (decoder.isCompleted()) {
            sink.close();
        }

    } catch (IOException e) {
        handleException("I/O Error : " + e.getMessage(), e, conn);
    }
}