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

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

Introduction

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

Prototype

Header[] getAllHeaders();

Source Link

Usage

From source file:jp.yojio.triplog.Common.DataApi.gdata.AndroidGDataClient.java

private InputStream createAndExecuteMethod(HttpRequestCreator creator, String uriString, String authToken)
        throws HttpException, IOException {

    HttpResponse response = null;//from  w  ww  .ja  va  2  s . co  m
    int status = 500;
    int redirectsLeft = MAX_REDIRECTS;

    URI uri;
    try {
        uri = new URI(uriString);
    } catch (URISyntaxException use) {
        Log.w(TAG, "Unable to parse " + uriString + " as URI.", use);
        throw new IOException("Unable to parse " + uriString + " as URI: " + use.getMessage());
    }

    // we follow redirects ourselves, since we want to follow redirects even on
    // POSTs, which
    // the HTTP library does not do. following redirects ourselves also allows
    // us to log
    // the redirects using our own logging.
    while (redirectsLeft > 0) {

        HttpUriRequest request = creator.createRequest(uri);
        request.addHeader("Accept-Encoding", "gzip");

        // only add the auth token if not null (to allow for GData feeds that do
        // not require
        // authentication.)
        if (!TextUtils.isEmpty(authToken)) {
            request.addHeader("Authorization", "GoogleLogin auth=" + authToken);
        }
        if (LOCAL_LOGV) {
            for (Header h : request.getAllHeaders()) {
                Log.v(TAG, h.getName() + ": " + h.getValue());
            }
            Log.d(TAG, "Executing " + request.getRequestLine().toString());
        }

        response = null;

        try {
            response = httpClient.execute(request);
        } catch (IOException ioe) {
            Log.w(TAG, "Unable to execute HTTP request." + ioe);
            throw ioe;
        }

        StatusLine statusLine = response.getStatusLine();
        if (statusLine == null) {
            Log.w(TAG, "StatusLine is null.");
            throw new NullPointerException("StatusLine is null -- should not happen.");
        }

        if (Log.isLoggable(TAG, Log.DEBUG)) {
            Log.d(TAG, response.getStatusLine().toString());
            for (Header h : response.getAllHeaders()) {
                Log.d(TAG, h.getName() + ": " + h.getValue());
            }
        }
        status = statusLine.getStatusCode();

        HttpEntity entity = response.getEntity();

        if ((status >= 200) && (status < 300) && entity != null) {
            return getUngzippedContent(entity);
        }

        // TODO: handle 301, 307?
        // TODO: let the http client handle the redirects, if we can be sure we'll
        // never get a
        // redirect on POST.
        if (status == 302) {
            // consume the content, so the connection can be closed.
            entity.consumeContent();
            Header location = response.getFirstHeader("Location");
            if (location == null) {
                if (Log.isLoggable(TAG, Log.DEBUG)) {
                    Log.d(TAG, "Redirect requested but no Location " + "specified.");
                }
                break;
            }
            if (Log.isLoggable(TAG, Log.DEBUG)) {
                Log.d(TAG, "Following redirect to " + location.getValue());
            }
            try {
                uri = new URI(location.getValue());
            } catch (URISyntaxException use) {
                if (Log.isLoggable(TAG, Log.DEBUG)) {
                    Log.d(TAG, "Unable to parse " + location.getValue() + " as URI.", use);
                    throw new IOException("Unable to parse " + location.getValue() + " as URI.");
                }
                break;
            }
            --redirectsLeft;
        } else {
            break;
        }
    }

    if (Log.isLoggable(TAG, Log.VERBOSE)) {
        Log.v(TAG, "Received " + status + " status code.");
    }
    String errorMessage = null;
    HttpEntity entity = response.getEntity();
    try {
        if (response != null && entity != null) {
            InputStream in = entity.getContent();
            ByteArrayOutputStream baos = new ByteArrayOutputStream();
            byte[] buf = new byte[8192];
            int bytesRead = -1;
            while ((bytesRead = in.read(buf)) != -1) {
                baos.write(buf, 0, bytesRead);
            }
            // TODO: use appropriate encoding, picked up from Content-Type.
            errorMessage = new String(baos.toByteArray());
            if (Log.isLoggable(TAG, Log.VERBOSE)) {
                Log.v(TAG, errorMessage);
            }
        }
    } finally {
        if (entity != null) {
            entity.consumeContent();
        }
    }
    String exceptionMessage = "Received " + status + " status code";
    if (errorMessage != null) {
        exceptionMessage += (": " + errorMessage);
    }
    throw new HttpException(exceptionMessage, status, null /* InputStream */);
}

From source file:br.com.bioscada.apps.biotracks.io.gdata.AndroidGDataClient.java

private InputStream createAndExecuteMethod(HttpRequestCreator creator, String uriString, String authToken)
        throws HttpException, IOException {

    HttpResponse response = null;/*from   w  w  w.j  a v a2  s .  co  m*/
    int status = 500;
    int redirectsLeft = MAX_REDIRECTS;

    URI uri;
    try {
        uri = new URI(uriString);
    } catch (URISyntaxException use) {
        Log.w(TAG, "Unable to parse " + uriString + " as URI.", use);
        throw new IOException("Unable to parse " + uriString + " as URI: " + use.getMessage());
    }

    // we follow redirects ourselves, since we want to follow redirects even on
    // POSTs, which
    // the HTTP library does not do. following redirects ourselves also allows
    // us to log
    // the redirects using our own logging.
    while (redirectsLeft > 0) {

        HttpUriRequest request = creator.createRequest(uri);
        request.addHeader("User-Agent", "Android-GData");
        request.addHeader("Accept-Encoding", "gzip");

        // only add the auth token if not null (to allow for GData feeds that do
        // not require
        // authentication.)
        if (!TextUtils.isEmpty(authToken)) {
            request.addHeader("Authorization", "GoogleLogin auth=" + authToken);
        }
        if (DEBUG) {
            for (Header h : request.getAllHeaders()) {
                Log.v(TAG, h.getName() + ": " + h.getValue());
            }
            Log.d(TAG, "Executing " + request.getRequestLine().toString());
        }

        response = null;

        try {
            response = httpClient.execute(request);
        } catch (IOException ioe) {
            Log.w(TAG, "Unable to execute HTTP request." + ioe);
            throw ioe;
        }

        StatusLine statusLine = response.getStatusLine();
        if (statusLine == null) {
            Log.w(TAG, "StatusLine is null.");
            throw new NullPointerException("StatusLine is null -- should not happen.");
        }

        if (Log.isLoggable(TAG, Log.DEBUG)) {
            Log.d(TAG, response.getStatusLine().toString());
            for (Header h : response.getAllHeaders()) {
                Log.d(TAG, h.getName() + ": " + h.getValue());
            }
        }
        status = statusLine.getStatusCode();

        HttpEntity entity = response.getEntity();

        if ((status >= 200) && (status < 300) && entity != null) {
            return getUngzippedContent(entity);
        }

        // TODO: handle 301, 307?
        // TODO: let the http client handle the redirects, if we can be sure we'll
        // never get a
        // redirect on POST.
        if (status == 302) {
            // consume the content, so the connection can be closed.
            entity.consumeContent();
            Header location = response.getFirstHeader("Location");
            if (location == null) {
                if (Log.isLoggable(TAG, Log.DEBUG)) {
                    Log.d(TAG, "Redirect requested but no Location " + "specified.");
                }
                break;
            }
            if (Log.isLoggable(TAG, Log.DEBUG)) {
                Log.d(TAG, "Following redirect to " + location.getValue());
            }
            try {
                uri = new URI(location.getValue());
            } catch (URISyntaxException use) {
                if (Log.isLoggable(TAG, Log.DEBUG)) {
                    Log.d(TAG, "Unable to parse " + location.getValue() + " as URI.", use);
                    throw new IOException("Unable to parse " + location.getValue() + " as URI.");
                }
                break;
            }
            --redirectsLeft;
        } else {
            break;
        }
    }

    if (Log.isLoggable(TAG, Log.VERBOSE)) {
        Log.v(TAG, "Received " + status + " status code.");
    }
    String errorMessage = null;
    HttpEntity entity = response.getEntity();
    try {
        if (entity != null) {
            InputStream in = entity.getContent();
            ByteArrayOutputStream baos = new ByteArrayOutputStream();
            byte[] buf = new byte[8192];
            int bytesRead = -1;
            while ((bytesRead = in.read(buf)) != -1) {
                baos.write(buf, 0, bytesRead);
            }
            // TODO: use appropriate encoding, picked up from Content-Type.
            errorMessage = new String(baos.toByteArray());
            if (Log.isLoggable(TAG, Log.VERBOSE)) {
                Log.v(TAG, errorMessage);
            }
        }
    } finally {
        if (entity != null) {
            entity.consumeContent();
        }
    }
    String exceptionMessage = "Received " + status + " status code";
    if (errorMessage != null) {
        exceptionMessage += (": " + errorMessage);
    }
    throw new HttpException(exceptionMessage, status, null /* InputStream */);
}

From source file:org.elasticsearch.client.RestClientSingleHostTests.java

/**
 * Verifies the content of the {@link HttpRequest} that's internally created and passed through to the http client
 *//* w  ww.j  a  v a  2s  .  c o  m*/
@SuppressWarnings("unchecked")
public void testInternalHttpRequest() throws Exception {
    ArgumentCaptor<HttpAsyncRequestProducer> requestArgumentCaptor = ArgumentCaptor
            .forClass(HttpAsyncRequestProducer.class);
    int times = 0;
    for (String httpMethod : getHttpMethods()) {
        HttpUriRequest expectedRequest = performRandomRequest(httpMethod);
        verify(httpClient, times(++times)).<HttpResponse>execute(requestArgumentCaptor.capture(),
                any(HttpAsyncResponseConsumer.class), any(HttpClientContext.class), any(FutureCallback.class));
        HttpUriRequest actualRequest = (HttpUriRequest) requestArgumentCaptor.getValue().generateRequest();
        assertEquals(expectedRequest.getURI(), actualRequest.getURI());
        assertEquals(expectedRequest.getClass(), actualRequest.getClass());
        assertArrayEquals(expectedRequest.getAllHeaders(), actualRequest.getAllHeaders());
        if (expectedRequest instanceof HttpEntityEnclosingRequest) {
            HttpEntity expectedEntity = ((HttpEntityEnclosingRequest) expectedRequest).getEntity();
            if (expectedEntity != null) {
                HttpEntity actualEntity = ((HttpEntityEnclosingRequest) actualRequest).getEntity();
                assertEquals(EntityUtils.toString(expectedEntity), EntityUtils.toString(actualEntity));
            }
        }
    }
}

From source file:com.example.fertilizercrm.common.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 w  w  w  .  j  av  a  2  s  .c  o  m*/
protected RequestHandle sendRequest(DefaultHttpClient client, HttpContext httpContext,
        HttpUriRequest uriRequest, String contentType, ResponseHandlerInterface responseHandler,
        Context context) {
    if (contentType != null) {
        uriRequest.setHeader("Content-Type", contentType);
    }

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

    Future<?> request = threadPool
            .submit(new AsyncHttpRequest(client, httpContext, uriRequest, responseHandler));

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

        requestList.add(new WeakReference<Future<?>>(request));
    }

    return new RequestHandle(request);
}

From source file:com.aoeng.degu.utils.net.asyncthhpclient.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  . java 2 s.  co  m*/
protected RequestHandle sendRequest(DefaultHttpClient client, HttpContext httpContext,
        HttpUriRequest uriRequest, String contentType, ResponseHandlerInterface responseHandler,
        Context context) {
    if (contentType != null) {
        uriRequest.setHeader("Content-Type", contentType);
    }

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

    Future<?> request = threadPool
            .submit(new AsyncHttpRequest(client, httpContext, uriRequest, responseHandler));

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

        requestList.add(new WeakReference<Future<?>>(request));

        // TODO: Remove dead weakrefs from requestLists?
    }

    return new RequestHandle(request);
}

From source file:cn.rongcloud.im.server.network.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  w  w  w  .  j a  va  2  s  .  c  om*/
protected RequestHandle sendRequest(DefaultHttpClient client, HttpContext httpContext,
        HttpUriRequest uriRequest, String contentType, ResponseHandlerInterface responseHandler,
        Context context) {
    if (contentType != null) {
        uriRequest.addHeader("Content-Type", contentType);
    }

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

    Future<?> request = threadPool
            .submit(new AsyncHttpRequest(client, httpContext, uriRequest, responseHandler));

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

        requestList.add(new WeakReference<Future<?>>(request));

        // TODO: Remove dead weakrefs from requestLists?
    }

    return new RequestHandle(request);
}

From source file:com.enjoy.nerd.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
 */// www .ja  v a  2 s .c o m
protected RequestHandle sendRequest(DefaultHttpClient client, HttpContext httpContext,
        HttpUriRequest uriRequest, String contentType, ResponseHandlerInterface responseHandler,
        Context context) {
    if (contentType != null) {
        uriRequest.setHeader("Content-Type", contentType);
    }

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

    //tangwh  add, ?????cookie?cookie?setCookieStore?uriRequestHeader?
    //??http2Cookie???cookieStore
    client.setCookieStore(null);

    Future<?> request = threadPool
            .submit(new AsyncHttpRequest(client, httpContext, uriRequest, responseHandler));

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

        requestList.add(new WeakReference<Future<?>>(request));

        // TODO: Remove dead weakrefs from requestLists?
    }

    return new RequestHandle(request);
}

From source file:com.flyn.net.asynchttp.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 ww.  j a  va  2s .  c  om
 * @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 (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);
        }

        requestList.add(requestHandle);

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

    return requestHandle;
}

From source file:org.dasein.cloud.azure.AzureMethod.java

public @Nullable InputStream getAsStream(@Nonnull String account, @Nonnull String resource)
        throws CloudException, InternalException {
    if (logger.isTraceEnabled()) {
        logger.trace("enter - " + AzureMethod.class.getName() + ".get(" + account + "," + resource + ")");
    }/*from   w  w w. j ava2s  .c  om*/
    if (wire.isDebugEnabled()) {
        wire.debug(
                "--------------------------------------------------------> " + endpoint + account + resource);
        wire.debug("");
    }
    try {
        HttpClient client = getClient();
        HttpUriRequest get = new HttpGet(endpoint + account + resource);

        //get.addHeader("Content-Type", "application/xml");
        get.addHeader("x-ms-version", "2012-03-01");
        if (wire.isDebugEnabled()) {
            wire.debug(get.getRequestLine().toString());
            for (Header header : get.getAllHeaders()) {
                wire.debug(header.getName() + ": " + header.getValue());
            }
            wire.debug("");
        }
        HttpResponse response;
        StatusLine status;

        try {
            response = client.execute(get);
            status = response.getStatusLine();
        } catch (IOException e) {
            logger.error("get(): Failed to execute HTTP request due to a cloud I/O error: " + e.getMessage());
            e.printStackTrace();
            throw new CloudException(e);
        }
        if (logger.isDebugEnabled()) {
            logger.debug("get(): HTTP Status " + status);
        }
        Header[] headers = response.getAllHeaders();

        if (wire.isDebugEnabled()) {
            wire.debug(status.toString());
            for (Header h : headers) {
                if (h.getValue() != null) {
                    wire.debug(h.getName() + ": " + h.getValue().trim());
                } else {
                    wire.debug(h.getName() + ":");
                }
            }
            wire.debug("");
        }
        if (status.getStatusCode() == HttpServletResponse.SC_NOT_FOUND) {
            return null;
        }
        if (status.getStatusCode() != HttpServletResponse.SC_OK
                && status.getStatusCode() != HttpServletResponse.SC_NON_AUTHORITATIVE_INFORMATION) {
            logger.error("get(): Expected OK for GET request, got " + status.getStatusCode());

            HttpEntity entity = response.getEntity();
            String body;

            if (entity == null) {
                throw new AzureException(CloudErrorType.GENERAL, status.getStatusCode(),
                        status.getReasonPhrase(), "An error was returned without explanation");
            }
            try {
                body = EntityUtils.toString(entity);
            } catch (IOException e) {
                throw new AzureException(CloudErrorType.GENERAL, status.getStatusCode(),
                        status.getReasonPhrase(), e.getMessage());
            }
            if (wire.isDebugEnabled()) {
                wire.debug(body);
            }
            wire.debug("");
            AzureException.ExceptionItems items = AzureException.parseException(status.getStatusCode(), body);

            if (items == null) {
                return null;
            }
            logger.error("get(): [" + status.getStatusCode() + " : " + items.message + "] " + items.details);
            throw new AzureException(items);
        } else {
            HttpEntity entity = response.getEntity();

            if (entity == null) {
                return null;
            }
            InputStream input;

            try {
                input = entity.getContent();
            } catch (IOException e) {
                logger.error(
                        "get(): Failed to read response error due to a cloud I/O error: " + e.getMessage());
                e.printStackTrace();
                throw new CloudException(e);
            }
            if (wire.isDebugEnabled()) {
                wire.debug("---> Binary Data <---");
            }
            wire.debug("");
            return input;
        }
    } finally {
        if (logger.isTraceEnabled()) {
            logger.trace("exit - " + AzureMethod.class.getName() + ".getStream()");
        }
        if (wire.isDebugEnabled()) {
            wire.debug("");
            wire.debug("--------------------------------------------------------> " + endpoint + account
                    + resource);
        }
    }
}

From source file:com.hypers.frame.http.core.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
 *//*  w w w .ja  v a2s.co  m*/
protected RequestHandle sendRequest(DefaultHttpClient client, HttpContext httpContext,
        HttpUriRequest uriRequest, String contentType, ResponseHandlerInterface responseHandler,
        Context context) {
    if (contentType != null) {
        uriRequest.setHeader("Content-Type", contentType);
    }
    //        //token
    //        uriRequest.addHeader("token", UserDataManger.getToken(context));

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

    Future<?> request = threadPool
            .submit(new AsyncHttpRequest(client, httpContext, uriRequest, responseHandler));

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

        requestList.add(new WeakReference<Future<?>>(request));

        // TODO: Remove dead weakrefs from requestLists?
    }

    return new RequestHandle(request);
}