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

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

Introduction

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

Prototype

boolean containsHeader(String str);

Source Link

Usage

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.  j  a  v  a 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:cn.openwatch.internal.http.loopj.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//from   w w  w  . j av  a 2s .  c o m
 * @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
 */
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() && !responseHandler.getUsePoolThread()) {
        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) {
        if (uriRequest instanceof HttpEntityEnclosingRequestBase
                && ((HttpEntityEnclosingRequestBase) uriRequest).getEntity() != null
                && uriRequest.containsHeader(HEADER_CONTENT_TYPE)) {
        } else {
            uriRequest.setHeader(HEADER_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) {
        List<RequestHandle> requestList;
        // Add request to request map
        synchronized (requestMap) {
            requestList = requestMap.get(context);
            if (requestList == null) {
                requestList = Collections.synchronizedList(new LinkedList<RequestHandle>());
                requestMap.put(context, requestList);
            }
        }

        requestList.add(requestHandle);

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

    return requestHandle;
}

From source file:org.apache.camel.component.olingo2.api.impl.Olingo2AppImpl.java

/**
 * public for unit test, not to be used otherwise
 *///from w w w . ja  v a 2  s . co  m
public void execute(HttpUriRequest httpUriRequest, ContentType contentType,
        FutureCallback<HttpResponse> callback) {

    // add accept header when its not a form or multipart
    final String contentTypeString = contentType.toString();
    if (!ContentType.APPLICATION_FORM_URLENCODED.getMimeType().equals(contentType.getMimeType())
            && !contentType.getMimeType().startsWith(MULTIPART_MIME_TYPE)) {
        // otherwise accept what is being sent
        httpUriRequest.addHeader(HttpHeaders.ACCEPT, contentTypeString);
    }
    // is something being sent?
    if (httpUriRequest instanceof HttpEntityEnclosingRequestBase
            && httpUriRequest.getFirstHeader(HttpHeaders.CONTENT_TYPE) == null) {
        httpUriRequest.addHeader(HttpHeaders.CONTENT_TYPE, contentTypeString);
    }

    // set user specified custom headers
    if (httpHeaders != null && !httpHeaders.isEmpty()) {
        for (Map.Entry<String, String> entry : httpHeaders.entrySet()) {
            httpUriRequest.setHeader(entry.getKey(), entry.getValue());
        }
    }

    // add client protocol version if not specified
    if (!httpUriRequest.containsHeader(ODataHttpHeaders.DATASERVICEVERSION)) {
        httpUriRequest.addHeader(ODataHttpHeaders.DATASERVICEVERSION, ODataServiceVersion.V20);
    }
    if (!httpUriRequest.containsHeader(MAX_DATA_SERVICE_VERSION)) {
        httpUriRequest.addHeader(MAX_DATA_SERVICE_VERSION, ODataServiceVersion.V30);
    }

    // execute request
    client.execute(httpUriRequest, callback);
}

From source file:net.www_eee.portal.channels.ProxyChannel.java

/**
 * Construct the value for the &quot;Authorization&quot; header to be {@link HttpUriRequest#setHeader(String, String)
 * set} on the {@link HttpUriRequest} being used to
 * {@linkplain #createProxyRequest(Page.Request, Channel.Mode, CloseableHttpClient) proxy} content to the
 * <code>proxiedFileURL</code>.
 * /*from ww w .j  a v  a2  s  .  c om*/
 * @param pageRequest The {@link net.www_eee.portal.Page.Request Request} currently being processed.
 * @param mode The {@link net.www_eee.portal.Channel.Mode Mode} of the request.
 * @param proxyClient The {@link #createProxyClient(Page.Request) HttpClient} performing the proxy request.
 * @param proxiedFileURL The {@linkplain #getProxiedFileURL(Page.Request, Channel.Mode, boolean) proxied file URL}.
 * @param proxyRequest The proxy {@link #createProxyRequestObject(Page.Request, Channel.Mode, URL) HttpUriRequest}
 * object.
 * @return The &quot;Authorization&quot; header value.
 * @throws WWWEEEPortal.Exception If a problem occurred while determining the result.
 * @throws WebApplicationException If a problem occurred while determining the result.
 * @see #createProxyRequest(Page.Request, Channel.Mode, CloseableHttpClient)
 */
protected @Nullable String getProxyRequestAuthorizationHeader(final Page.Request pageRequest, final Mode mode,
        final HttpClient proxyClient, final URL proxiedFileURL, final HttpUriRequest proxyRequest)
        throws WWWEEEPortal.Exception, WebApplicationException {
    if ((!proxyRequest.containsHeader("Authorization")) && (RESTUtil
            .getFirstHeaderValue(pageRequest.getHttpHeaders(), "Authorization", Function.identity()) != null)) {
        return RESTUtil.getFirstHeaderValue(pageRequest.getHttpHeaders(), "Authorization", Function.identity())
                .orElse(null);
    }
    return null;
}

From source file:cn.com.loopj.android.http.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.ja  v  a2  s .c  o m*/
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() && !responseHandler.getUsePoolThread()) {
        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) {
        if (uriRequest instanceof HttpEntityEnclosingRequestBase
                && ((HttpEntityEnclosingRequestBase) uriRequest).getEntity() != null
                && uriRequest.containsHeader(HEADER_CONTENT_TYPE)) {
            log.w(LOG_TAG, "Passed contentType will be ignored because HttpEntity sets content type");
        } else {
            uriRequest.setHeader(HEADER_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) {
        List<RequestHandle> requestList;
        // Add request to request map
        synchronized (requestMap) {
            requestList = requestMap.get(context);
            if (requestList == null) {
                requestList = Collections.synchronizedList(new LinkedList<RequestHandle>());
                requestMap.put(context, requestList);
            }
        }

        requestList.add(requestHandle);

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

    return requestHandle;
}

From source file:com.amytech.android.library.utils.asynchttp.AsyncHttpClient.java

/**
 * Puts a new request in queue as a new thread in pool to be executed
 *
 * @param client/*from  ww w  .  j a  v a 2 s.c  om*/
 *            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
 */
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() && !responseHandler.getUsePoolThread()) {
        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) {
        if (uriRequest instanceof HttpEntityEnclosingRequestBase
                && ((HttpEntityEnclosingRequestBase) uriRequest).getEntity() != null
                && uriRequest.containsHeader(HEADER_CONTENT_TYPE)) {
            Log.w(LOG_TAG, "Passed contentType will be ignored because HttpEntity sets content type");
        } else {
            uriRequest.setHeader(HEADER_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) {
        List<RequestHandle> requestList;
        // Add request to request map
        synchronized (requestMap) {
            requestList = requestMap.get(context);
            if (requestList == null) {
                requestList = Collections.synchronizedList(new LinkedList<RequestHandle>());
                requestMap.put(context, requestList);
            }
        }

        requestList.add(requestHandle);

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

    return requestHandle;
}

From source file:org.fcrepo.integration.http.api.AbstractResourceIT.java

/**
 * Executes an HTTP request and parses the RDF found in the response, returning it in a
 * {@link CloseableDataset}, then closes the response.
 *
 * @param client the client to use/*from   w w  w.  j av  a2s.c o  m*/
 * @param req the request to execute
 * @return the graph retrieved
 * @throws IOException in case of IOException
 */
private CloseableDataset getDataset(final CloseableHttpClient client, final HttpUriRequest req)
        throws IOException {
    if (!req.containsHeader(ACCEPT)) {
        req.addHeader(ACCEPT, "application/n-triples");
    }
    logger.debug("Retrieving RDF using mimeType: {}", req.getFirstHeader(ACCEPT));

    try (final CloseableHttpResponse response = client.execute(req)) {
        assertEquals(OK.getStatusCode(), response.getStatusLine().getStatusCode());
        final CloseableDataset result = parseTriples(response.getEntity());
        logger.trace("Retrieved RDF: {}", result);
        return result;
    }

}

From source file:synapticloop.b2.request.BaseB2Request.java

/**
 * Set the headers safely, go through the headers Map and add them to the http
 * request with properly encode values.  If they already exist on the http
 * request, it will be ignored./*  ww w .  j  a v a  2 s.co  m*/
 *
 * To override what headers are set, this should be done in the constructor
 * of the base request object.
 *
 * @param request The HTTP request to set the headers on
 *
 * @throws B2ApiException if there was an error setting the headers
 */
protected void setHeaders(HttpUriRequest request) throws B2ApiException {
    for (String headerKey : requestHeaders.keySet()) {
        if (!request.containsHeader(headerKey)) {
            final String headerValue = requestHeaders.get(headerKey);
            LOGGER.trace("Setting header '" + headerKey + "' to '" + headerValue + "'.");
            request.setHeader(headerKey, headerValue);
        } else {
            LOGGER.warn("Ignore duplicate header " + headerKey);
        }
    }
}