Example usage for org.apache.http.client.methods HttpRequestWrapper getMethod

List of usage examples for org.apache.http.client.methods HttpRequestWrapper getMethod

Introduction

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

Prototype

public String getMethod() 

Source Link

Usage

From source file:com.flipkart.phantom.http.impl.HttpProxy.java

/**
 * The main method which makes the HTTP request
 *///from w w  w. ja  v  a  2 s .co  m
public HttpResponse doRequest(HttpRequestWrapper httpRequestWrapper) throws Exception {
    /** get necessary data required for the output */
    return pool.execute(createRequest(httpRequestWrapper.getMethod(), httpRequestWrapper.getUri(),
            httpRequestWrapper.getData()), httpRequestWrapper.getHeaders());
}

From source file:com.smartsheet.api.internal.http.DefaultHttpClient.java

/**
 * Make an HTTP request and return the response.
 *
 * @param smartsheetRequest the smartsheet request
 * @return the HTTP response/*from  ww w  .ja  v a2s  .c o m*/
 * @throws HttpClientException the HTTP client exception
 */
public HttpResponse request(HttpRequest smartsheetRequest) throws HttpClientException {
    Util.throwIfNull(smartsheetRequest);
    if (smartsheetRequest.getUri() == null) {
        throw new IllegalArgumentException("A Request URI is required.");
    }

    int attempt = 0;
    long start = System.currentTimeMillis();

    HttpRequestBase apacheHttpRequest;
    HttpResponse smartsheetResponse;

    InputStream bodyStream = null;
    if (smartsheetRequest.getEntity() != null && smartsheetRequest.getEntity().getContent() != null) {
        bodyStream = smartsheetRequest.getEntity().getContent();
    }
    // the retry logic will consume the body stream so we make sure it supports mark/reset and mark it
    boolean canRetryRequest = bodyStream == null || bodyStream.markSupported();
    if (!canRetryRequest) {
        try {
            // attempt to wrap the body stream in a input-stream that does support mark/reset
            bodyStream = new ByteArrayInputStream(StreamUtil.readBytesFromStream(bodyStream));
            // close the old stream (just to be tidy) and then replace it with a reset-able stream
            smartsheetRequest.getEntity().getContent().close();
            smartsheetRequest.getEntity().setContent(bodyStream);
            canRetryRequest = true;
        } catch (IOException ignore) {
        }
    }

    // the retry loop
    while (true) {

        apacheHttpRequest = createApacheRequest(smartsheetRequest);

        // Set HTTP headers
        if (smartsheetRequest.getHeaders() != null) {
            for (Map.Entry<String, String> header : smartsheetRequest.getHeaders().entrySet()) {
                apacheHttpRequest.addHeader(header.getKey(), header.getValue());
            }
        }

        HttpEntitySnapshot requestEntityCopy = null;
        HttpEntitySnapshot responseEntityCopy = null;
        // Set HTTP entity
        final HttpEntity entity = smartsheetRequest.getEntity();
        if (apacheHttpRequest instanceof HttpEntityEnclosingRequestBase && entity != null
                && entity.getContent() != null) {
            try {
                // we need access to the original request stream so we can log it (in the event of errors and/or tracing)
                requestEntityCopy = new HttpEntitySnapshot(entity);
            } catch (IOException iox) {
                logger.error("failed to make copy of original request entity - {}", iox);
            }

            InputStreamEntity streamEntity = new InputStreamEntity(entity.getContent(),
                    entity.getContentLength());
            streamEntity.setChunked(false); // why?  not supported by library?
            ((HttpEntityEnclosingRequestBase) apacheHttpRequest).setEntity(streamEntity);
        }

        // mark the body so we can reset on retry
        if (canRetryRequest && bodyStream != null) {
            bodyStream.mark((int) smartsheetRequest.getEntity().getContentLength());
        }

        // Make the HTTP request
        smartsheetResponse = new HttpResponse();
        HttpContext context = new BasicHttpContext();
        try {
            long startTime = System.currentTimeMillis();
            apacheHttpResponse = this.httpClient.execute(apacheHttpRequest, context);
            long endTime = System.currentTimeMillis();

            // Set request headers to values ACTUALLY SENT (not just created by us), this would include:
            // 'Connection', 'Accept-Encoding', etc. However, if a proxy is used, this may be the proxy's CONNECT
            // request, hence the test for HTTP method first
            Object httpRequest = context.getAttribute("http.request");
            if (httpRequest != null && HttpRequestWrapper.class.isAssignableFrom(httpRequest.getClass())) {
                HttpRequestWrapper actualRequest = (HttpRequestWrapper) httpRequest;
                switch (HttpMethod.valueOf(actualRequest.getMethod())) {
                case GET:
                case POST:
                case PUT:
                case DELETE:
                    apacheHttpRequest.setHeaders(((HttpRequestWrapper) httpRequest).getAllHeaders());
                    break;
                }
            }

            // Set returned headers
            smartsheetResponse.setHeaders(new HashMap<String, String>());
            for (Header header : apacheHttpResponse.getAllHeaders()) {
                smartsheetResponse.getHeaders().put(header.getName(), header.getValue());
            }
            smartsheetResponse.setStatus(apacheHttpResponse.getStatusLine().getStatusCode(),
                    apacheHttpResponse.getStatusLine().toString());

            // Set returned entities
            if (apacheHttpResponse.getEntity() != null) {
                HttpEntity httpEntity = new HttpEntity();
                httpEntity.setContentType(apacheHttpResponse.getEntity().getContentType().getValue());
                httpEntity.setContentLength(apacheHttpResponse.getEntity().getContentLength());
                httpEntity.setContent(apacheHttpResponse.getEntity().getContent());
                smartsheetResponse.setEntity(httpEntity);
                responseEntityCopy = new HttpEntitySnapshot(httpEntity);
            }

            long responseTime = endTime - startTime;
            logRequest(apacheHttpRequest, requestEntityCopy, smartsheetResponse, responseEntityCopy,
                    responseTime);

            if (traces.size() > 0) { // trace-logging of request and response (if so configured)
                RequestAndResponseData requestAndResponseData = RequestAndResponseData.of(apacheHttpRequest,
                        requestEntityCopy, smartsheetResponse, responseEntityCopy, traces);
                TRACE_WRITER.println(requestAndResponseData.toString(tracePrettyPrint));
            }

            if (smartsheetResponse.getStatusCode() == 200) {
                // call successful, exit the retry loop
                break;
            }

            // the retry logic might consume the content stream so we make sure it supports mark/reset and mark it
            InputStream contentStream = smartsheetResponse.getEntity().getContent();
            if (!contentStream.markSupported()) {
                // wrap the response stream in a input-stream that does support mark/reset
                contentStream = new ByteArrayInputStream(StreamUtil.readBytesFromStream(contentStream));
                // close the old stream (just to be tidy) and then replace it with a reset-able stream
                smartsheetResponse.getEntity().getContent().close();
                smartsheetResponse.getEntity().setContent(contentStream);
            }
            try {
                contentStream.mark((int) smartsheetResponse.getEntity().getContentLength());
                long timeSpent = System.currentTimeMillis() - start;
                if (!shouldRetry(++attempt, timeSpent, smartsheetResponse)) {
                    // should not retry, or retry time exceeded, exit the retry loop
                    break;
                }
            } finally {
                if (bodyStream != null) {
                    bodyStream.reset();
                }
                contentStream.reset();
            }
            // moving this to finally causes issues because socket is closed (which means response stream is closed)
            this.releaseConnection();

        } catch (ClientProtocolException e) {
            try {
                logger.warn("ClientProtocolException " + e.getMessage());
                logger.warn("{}", RequestAndResponseData.of(apacheHttpRequest, requestEntityCopy,
                        smartsheetResponse, responseEntityCopy, REQUEST_RESPONSE_SUMMARY));
                // if this is a PUT and was retried by the http client, the body content stream is at the
                // end and is a NonRepeatableRequest. If we marked the body content stream prior to execute,
                // reset and retry
                if (canRetryRequest && e.getCause() instanceof NonRepeatableRequestException) {
                    if (smartsheetRequest.getEntity() != null) {
                        smartsheetRequest.getEntity().getContent().reset();
                    }
                    continue;
                }
            } catch (IOException ignore) {
            }
            throw new HttpClientException("Error occurred.", e);
        } catch (NoHttpResponseException e) {
            try {
                logger.warn("NoHttpResponseException " + e.getMessage());
                logger.warn("{}", RequestAndResponseData.of(apacheHttpRequest, requestEntityCopy,
                        smartsheetResponse, responseEntityCopy, REQUEST_RESPONSE_SUMMARY));
                // check to see if the response was empty and this was a POST. All other HTTP methods
                // will be automatically retried by the http client.
                // (POST is non-idempotent and is not retried automatically, but is safe for us to retry)
                if (canRetryRequest && smartsheetRequest.getMethod() == HttpMethod.POST) {
                    if (smartsheetRequest.getEntity() != null) {
                        smartsheetRequest.getEntity().getContent().reset();
                    }
                    continue;
                }
            } catch (IOException ignore) {
            }
            throw new HttpClientException("Error occurred.", e);
        } catch (IOException e) {
            try {
                logger.warn("{}", RequestAndResponseData.of(apacheHttpRequest, requestEntityCopy,
                        smartsheetResponse, responseEntityCopy, REQUEST_RESPONSE_SUMMARY));
            } catch (IOException ignore) {
            }
            throw new HttpClientException("Error occurred.", e);
        }
    }
    return smartsheetResponse;
}