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

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

Introduction

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

Prototype

String getMethod();

Source Link

Document

Returns the HTTP method this request uses, such as <code>GET</code>, <code>PUT</code>, <code>POST</code>, or other.

Usage

From source file:org.jets3t.service.impl.rest.httpclient.RestStorageService.java

/**
 * Performs an HTTP/S request by invoking the provided HttpMethod object. If the HTTP
 * response code doesn't match the expected value, an exception is thrown.
 *
 * @param httpMethod/* w ww. j ava 2s .  c om*/
 *        the object containing a request target and all other information necessary to perform the
 *        request
 * @param expectedResponseCodes
 *        the HTTP response code(s) that indicates a successful request. If the response code received
 *        does not match this value an error must have occurred, so an exception is thrown.
 * @param context
 *        An HttpContext to facilitate information sharing in the HTTP chain
 * @throws ServiceException
 *        all exceptions are wrapped in an ServiceException. Depending on the kind of error that
 *        occurred, this exception may contain additional error information available from an XML
 *        error response document.
 */
protected HttpResponse performRequest(HttpUriRequest httpMethod, int[] expectedResponseCodes,
        HttpContext context) throws ServiceException {
    HttpResponse response = null;
    InterfaceLogBean reqBean = new InterfaceLogBean(httpMethod.getURI().toString(), "", "");
    try {
        if (log.isDebugEnabled()) {
            log.debug("Performing " + httpMethod.getMethod() + " request for '" + httpMethod.getURI().toString()
                    + "', expecting response codes: " + "[" + ServiceUtils.join(expectedResponseCodes, ",")
                    + "]");
            log.debug("Headers: " + Arrays.asList(httpMethod.getAllHeaders()));
        }
        log.debug("Endpoint: " + getEndpoint());

        // Variables to manage S3 Internal Server 500 or 503 Service Unavailable errors.
        boolean completedWithoutRecoverableError = true;
        int internalErrorCount = 0;
        int requestTimeoutErrorCount = 0;
        int redirectCount = 0;
        int authFailureCount = 0;
        boolean wasRecentlyRedirected = false;

        // Perform the request, sleeping and retrying when errors are encountered.
        int responseCode = -1;
        do {
            // Build the authorization string for the method (Unless we have just been redirected).
            if (!wasRecentlyRedirected) {
                authorizeHttpRequest(httpMethod, context);
            } else {
                // Reset redirection flag
                wasRecentlyRedirected = false;
            }

            response = httpClient.execute(httpMethod, context);
            responseCode = response.getStatusLine().getStatusCode();
            reqBean.setRespParams("[responseCode: " + responseCode + "][x-amz-request-id: "
                    + response.getFirstHeader("x-amz-request-id").getValue() + "]");
            if (responseCode == 307) {
                // Retry on Temporary Redirects, using new URI from location header
                authorizeHttpRequest(httpMethod, context); // Re-authorize *before* we change the URI
                Header locationHeader = response.getFirstHeader("location");

                // deal with implementations of HttpUriRequest
                if (httpMethod instanceof HttpRequestBase) {
                    ((HttpRequestBase) httpMethod).setURI(new URI(locationHeader.getValue()));
                } else if (httpMethod instanceof RequestWrapper) {
                    ((RequestWrapper) httpMethod).setURI(new URI(locationHeader.getValue()));
                }

                completedWithoutRecoverableError = false;
                redirectCount++;
                wasRecentlyRedirected = true;

                if (redirectCount > 5) {
                    reqBean.setResponseInfo("Exceeded 307 redirect limit (5).", "-1");
                    throw new ServiceException("Exceeded 307 redirect limit (5).");
                }
            } else if (responseCode == 500 || responseCode == 503) {
                // Retry on S3 Internal Server 500 or 503 Service Unavailable errors.
                completedWithoutRecoverableError = false;
                reqBean.setResponseInfo("Internal Server error(s).", "-1");
                ilog.error(reqBean);
                sleepOnInternalError(++internalErrorCount);
            } else {
                completedWithoutRecoverableError = true;
            }

            String contentType = "";
            if (response.getFirstHeader("Content-Type") != null) {
                contentType = response.getFirstHeader("Content-Type").getValue();
            }
            if (log.isDebugEnabled()) {
                log.debug("Response for '" + httpMethod.getMethod() + "'. Content-Type: " + contentType
                        + ", Headers: " + Arrays.asList(response.getAllHeaders()));
                log.debug("Response entity: " + response.getEntity());
                if (response.getEntity() != null) {
                    log.debug("Entity length: " + response.getEntity().getContentLength());
                }
            }

            // Check we received the expected result code.
            boolean didReceiveExpectedResponseCode = false;
            for (int i = 0; i < expectedResponseCodes.length && !didReceiveExpectedResponseCode; i++) {
                if (responseCode == expectedResponseCodes[i]) {
                    didReceiveExpectedResponseCode = true;
                }
            }
            if (log.isDebugEnabled()) {
                log.debug("Received expected response code: " + didReceiveExpectedResponseCode);
                log.debug("  expected code(s): " + Arrays.toString(expectedResponseCodes) + ".");
            }

            if (!didReceiveExpectedResponseCode) {
                if (log.isDebugEnabled()) {
                    log.debug("Response xml: " + isXmlContentType(contentType));
                    log.debug("Response entity: " + response.getEntity());
                    log.debug("Response entity length: " + (response.getEntity() == null ? "??"
                            : "" + response.getEntity().getContentLength()));
                }

                if (response.getEntity() != null && response.getEntity().getContentLength() != 0) {
                    if (log.isDebugEnabled()) {
                        log.debug("Response '" + httpMethod.getURI().getRawPath()
                                + "' - Received error response with XML message");
                    }

                    StringBuilder sb = new StringBuilder();
                    BufferedReader reader = null;
                    try {
                        reader = new BufferedReader(
                                new InputStreamReader(new HttpMethodReleaseInputStream(response)));
                        String line = null;
                        while ((line = reader.readLine()) != null) {
                            sb.append(line).append("\n");
                        }
                    } finally {
                        if (reader != null) {
                            reader.close();
                        }
                    }

                    EntityUtils.consume(response.getEntity());

                    // Throw exception containing the XML message document.
                    ServiceException exception = new ServiceException("S3 Error Message.", sb.toString());

                    exception.setResponseCode(responseCode);
                    exception.setResponseHeaders(RestUtils.convertHeadersToMap(response.getAllHeaders()));
                    reqBean.setResponseInfo("http status: " + responseCode, exception.getErrorCode());
                    ilog.error(reqBean);
                    if ("RequestTimeout".equals(exception.getErrorCode())) {
                        int retryMaxCount = jets3tProperties.getIntProperty("httpclient.retry-max", 5);

                        if (requestTimeoutErrorCount < retryMaxCount) {
                            requestTimeoutErrorCount++;
                            if (log.isWarnEnabled()) {
                                log.warn("Retrying connection that failed with RequestTimeout error"
                                        + ", attempt number " + requestTimeoutErrorCount + " of "
                                        + retryMaxCount);
                            }
                            completedWithoutRecoverableError = false;
                        } else {
                            if (log.isErrorEnabled()) {
                                log.error("Exceeded maximum number of retries for RequestTimeout errors: "
                                        + retryMaxCount);
                            }
                            throw exception;
                        }
                    } else if ("RequestTimeTooSkewed".equals(exception.getErrorCode())) {
                        //                            this.timeOffset = RestUtils.getAWSTimeAdjustment();
                        if (log.isWarnEnabled()) {
                            log.warn("Adjusted time offset in response to RequestTimeTooSkewed error. "
                                    + "Local machine and S3 server disagree on the time by approximately "
                                    + (this.timeOffset / 1000) + " seconds. Retrying connection.");
                        }
                        completedWithoutRecoverableError = false;
                        throw new ServiceException("S3 Error Message.", sb.toString());
                    } else if (responseCode == 500 || responseCode == 503) {
                        // Retrying after 500 or 503 error, don't throw exception.
                    } else if (responseCode == 307) {
                        // Retrying after Temporary Redirect 307, don't throw exception.
                        if (log.isDebugEnabled()) {
                            log.debug("Following Temporary Redirect to: " + httpMethod.getURI().toString());
                        }
                    }

                    // Special handling for S3 object PUT failures causing NoSuchKey errors - Issue #85
                    else if (responseCode == 404 && "PUT".equalsIgnoreCase(httpMethod.getMethod())
                            && "NoSuchKey".equals(exception.getErrorCode())
                            // If PUT operation is trying to copy an existing source object, don't ignore 404
                            && httpMethod.getFirstHeader(getRestHeaderPrefix() + "copy-source") == null) {
                        // Retrying after mysterious PUT NoSuchKey error caused by S3, don't throw exception.
                        if (log.isDebugEnabled()) {
                            log.debug("Ignoring NoSuchKey/404 error on PUT to: "
                                    + httpMethod.getURI().toString());
                        }
                        completedWithoutRecoverableError = false;
                    }

                    else if ((responseCode == 403 || responseCode == 401)
                            && this.isRecoverable403(httpMethod, exception)) {
                        completedWithoutRecoverableError = false;
                        authFailureCount++;

                        if (authFailureCount > 1) {
                            throw new ServiceException("Exceeded 403 retry limit (1).");
                        }

                        if (log.isDebugEnabled()) {
                            log.debug("Retrying after 403 Forbidden");
                        }
                    }

                    else {
                        throw exception;
                    }
                } else {
                    reqBean.setResponseInfo("http status:" + responseCode, "-1");
                    ilog.error(reqBean);
                    // Consume response content and release connection.
                    String responseText = null;
                    byte[] responseBody = null;
                    if (response.getEntity() != null) {
                        responseBody = EntityUtils.toByteArray(response.getEntity());
                    }
                    if (responseBody != null && responseBody.length > 0) {
                        responseText = new String(responseBody);
                    }

                    if (log.isDebugEnabled()) {
                        log.debug("Releasing error response without XML content");
                    }
                    EntityUtils.consume(response.getEntity());

                    if (responseCode == 500 || responseCode == 503) {
                        // Retrying after InternalError 500, don't throw exception.
                    } else {
                        // Throw exception containing the HTTP error fields.
                        HttpException httpException = new HttpException(responseCode,
                                response.getStatusLine().getReasonPhrase());
                        ServiceException exception = new ServiceException(
                                "Request Error" + (responseText != null ? " [" + responseText + "]." : "."),
                                httpException);
                        reqBean.setResponseInfo(
                                "Request Error" + (responseText != null ? " [" + responseText + "]." : "."),
                                "-1");
                        ilog.error(reqBean);
                        exception.setResponseHeaders(RestUtils.convertHeadersToMap(response.getAllHeaders()));
                        throw exception;
                    }
                }

                // Print warning message if a non-fatal error occurred (we only reach this
                // point in the code if an exception isn't thrown above)
                if (log.isWarnEnabled()) {
                    String requestDescription = httpMethod.getMethod() + " '" + httpMethod.getURI().getPath()
                            + (httpMethod.getURI().getQuery() != null
                                    && httpMethod.getURI().getQuery().length() > 0
                                            ? "?" + httpMethod.getURI().getQuery()
                                            : "")
                            + "'" + " -- ResponseCode: " + responseCode + ", ResponseStatus: "
                            + response.getStatusLine().getReasonPhrase() + ", Request Headers: ["
                            + ServiceUtils.join(httpMethod.getAllHeaders(), ", ") + "]"
                            + ", Response Headers: [" + ServiceUtils.join(response.getAllHeaders(), ", ") + "]";
                    requestDescription = requestDescription.replaceAll("[\\n\\r\\f]", ""); // Remove any newlines.
                    log.warn("Error Response: " + requestDescription);
                }
            }
        } while (!completedWithoutRecoverableError);
    } catch (Throwable t) {
        if (log.isDebugEnabled()) {
            String msg = "Rethrowing as a ServiceException error in performRequest: " + t;
            if (t.getCause() != null) {
                msg += ", with cause: " + t.getCause();
            }
            if (log.isTraceEnabled()) {
                log.trace(msg, t);
            } else {
                log.debug(msg);
            }
        }
        if (log.isDebugEnabled() && !shuttingDown) {
            log.debug("Releasing HttpClient connection after error: " + t.getMessage());
        }
        httpMethod.abort();

        ServiceException serviceException;
        if (t instanceof ServiceException) {
            serviceException = (ServiceException) t;
        } else {
            MxDelegate.getInstance().registerS3ServiceExceptionEvent();
            serviceException = new ServiceException("Request Error: " + t, t);
        }

        // Add S3 request and host IDs from HTTP headers to exception, if they are available
        // and have not already been populated by parsing an XML error response.
        if (!serviceException.isParsedFromXmlMessage() && response != null
                && response.getFirstHeader(Constants.AMZ_REQUEST_ID_1) != null
                && response.getFirstHeader(Constants.AMZ_REQUEST_ID_2) != null) {
            serviceException.setRequestAndHostIds(
                    response.getFirstHeader(Constants.AMZ_REQUEST_ID_1).getValue(),
                    response.getFirstHeader(Constants.AMZ_REQUEST_ID_2).getValue());
            serviceException.setResponseHeaders(RestUtils.convertHeadersToMap(response.getAllHeaders()));
        }
        if (response != null) {
            try {
                serviceException.setResponseCode(response.getStatusLine().getStatusCode());
                serviceException.setResponseStatus(response.getStatusLine().getReasonPhrase());
            } catch (NullPointerException e) {
                // If no network connection is available, status info is not available
            }
        }
        if (httpMethod.getFirstHeader("Host") != null) {
            serviceException.setRequestHost(httpMethod.getFirstHeader("Host").getValue());
        }
        if (response != null && response.getFirstHeader("Date") != null) {
            serviceException.setResponseDate(response.getFirstHeader("Date").getValue());
        }
        reqBean.setResponseInfo(serviceException.getErrorMessage(), serviceException.getErrorCode());
        throw serviceException;
    }
    reqBean.setRespTime(new Date());
    reqBean.setTargetAddr(getEndpoint());
    reqBean.setResultCode("0");
    ilog.info(reqBean);
    return response;
}

From source file:org.deviceconnect.android.manager.setting.ReqResDebugActivity.java

/**
 * Http?.// w ww. j a  v  a 2  s. c om
 * @param request 
 * @param listener Http????
 */
private void executeHttpRequest(final HttpUriRequest request, final HttpListener listener) {
    if (!showProgressDialog()) {
        return;
    }
    AsyncTask<HttpUriRequest, HttpUriRequest, String> task = new AsyncTask<HttpUriRequest, HttpUriRequest, String>() {
        @Override
        protected String doInBackground(final HttpUriRequest... params) {
            if (params == null || params.length < 1) {
                return "Illegal Parameter.";
            }

            HttpUriRequest request = params[0];
            DefaultHttpClient client = new DefaultHttpClient();
            try {
                HttpResponse response = client.execute(request);
                switch (response.getStatusLine().getStatusCode()) {
                case HttpStatus.SC_OK:
                    try {
                        return EntityUtils.toString(response.getEntity(), "UTF-8");
                    } catch (ParseException e) {
                        return e.getMessage();
                    } catch (IOException e) {
                        return e.getMessage();
                    }
                case HttpStatus.SC_NOT_FOUND:
                    return "Not found. 404";
                default:
                    return "Http connect error.";
                }
            } catch (ClientProtocolException e) {
                return e.getMessage();
            } catch (IOException e) {
                return e.getMessage();
            } finally {
                client.getConnectionManager().shutdown();
            }
        }

        @Override
        protected void onPostExecute(final String response) {
            super.onPostExecute(response);

            hideProgressDialog();

            if (response == null) {
                return;
            }

            StringBuilder sb = new StringBuilder();
            sb.append("Request:\n");
            sb.append(request.getMethod() + " " + request.getURI() + "\n");
            mListAdapter.add(sb.toString());
            mListAdapter.add("Response:\n" + response);
            mListAdapter.notifyDataSetChanged();
            if (listener != null) {
                listener.onReceivedResponse(response);
            }
        }
    };
    task.execute(request);
}

From source file:com.fujitsu.dc.client.http.DcRequestBuilder.java

/**
 * This method is used to generate a HttpUriRequest object by setting the parameters in request header.
 * @return HttpUriRequest object that is generated
 * @throws DaoException Exception thrown
 *//*  w ww  .j  a v a2 s  . com*/
public HttpUriRequest build() throws DaoException {
    HttpUriRequest req = null;
    if (HttpMethods.PUT.equals(this.methodValue)) {
        req = new HttpPut(this.urlValue);
    } else if (HttpMethods.POST.equals(this.methodValue)) {
        req = new HttpPost(this.urlValue);
    } else if (HttpMethods.DELETE.equals(this.methodValue)) {
        req = new HttpDelete(this.urlValue);
    } else if (HttpMethods.ACL.equals(this.methodValue)) {
        req = new HttpAclMethod(this.urlValue);
    } else if (HttpMethods.MKCOL.equals(this.methodValue)) {
        req = new HttpMkColMethod(this.urlValue);
    } else if (HttpMethods.PROPPATCH.equals(this.methodValue)) {
        req = new HttpPropPatchMethod(this.urlValue);
    } else if (HttpMethods.PROPFIND.equals(this.methodValue)) {
        req = new HttpPropfindMethod(this.urlValue);
    } else if (HttpMethods.GET.equals(this.methodValue)) {
        req = new HttpGet(this.urlValue);
    } else if (HttpMethods.MERGE.equals(this.methodValue)) {
        req = new HttpMergeMethod(this.urlValue);
    }

    if (this.tokenValue != null) {
        req.addHeader(HttpHeaders.AUTHORIZATION, "Bearer " + this.tokenValue);
    }

    /** include header parameters if any. */
    for (String key : headers.keySet()) {
        String value = headers.get(key);
        req.addHeader(key, value);
    }

    // ????????
    /** If Default header is set, configure them. */
    // ?????????????????????
    /**
     * The reason you do not want to set for the first time, since the request header, would have been more than one
     * registration is the same name header
     */
    if (this.defaultHeaders != null) {
        for (String key : this.defaultHeaders.keySet()) {
            String val = this.defaultHeaders.get(key);
            Header[] headerItems = req.getHeaders(key);
            if (headerItems.length == 0) {
                req.addHeader(key, val);
            }
        }
    }
    if (this.bodyValue != null) {
        HttpEntity body = null;
        try {
            if (this.getContentType() != "" && RestAdapter.CONTENT_TYPE_JSON.equals(this.getContentType())) {
                String bodyStr = toUniversalCharacterNames(this.bodyValue);
                body = new StringEntity(bodyStr);
            } else {
                body = new StringEntity(this.bodyValue, RestAdapter.ENCODE);
            }
        } catch (UnsupportedEncodingException e) {
            throw DaoException.create("error while request body encoding : " + e.getMessage(), 0);
        }
        ((HttpEntityEnclosingRequest) req).setEntity(body);
    }
    if (this.bodyStream != null) {
        InputStreamEntity body = new InputStreamEntity(this.bodyStream, -1);
        body.setChunked(true);
        this.bodyValue = "[stream]";
        ((HttpEntityEnclosingRequest) req).setEntity(body);
    }
    if (req != null) {
        log.debug("");
        log.debug("?Request " + req.getMethod() + "  " + req.getURI());
        Header[] allheaders = req.getAllHeaders();
        for (int i = 0; i < allheaders.length; i++) {
            log.debug("RequestHeader[" + allheaders[i].getName() + "] : " + allheaders[i].getValue());
        }
        log.debug("RequestBody : " + bodyValue);
    }
    return req;
}

From source file:org.jets3t.service.impl.rest.httpclient.RestStorageService.java

/**
 * Authorizes an HTTP/S request by signing it with an HMAC signature compatible with
 * the S3 service and Google Storage (legacy) authorization techniques.
 *
 * The signature is added to the request as an Authorization header.
 *
 * @param httpMethod//from  ww w  .j  a v  a  2  s .  c o m
 * the request object
 * @throws ServiceException
 */
public void authorizeHttpRequest(HttpUriRequest httpMethod, HttpContext context) throws ServiceException {
    if (getProviderCredentials() != null) {
        if (log.isDebugEnabled()) {
            log.debug("Adding authorization for Access Key '" + getProviderCredentials().getAccessKey() + "'.");
        }
    } else {
        if (log.isDebugEnabled()) {
            log.debug("Service has no Credential and is un-authenticated, skipping authorization");
        }
        return;
    }

    URI uri = httpMethod.getURI();
    String hostname = uri.getHost();

    /*
     * Determine the complete URL for the S3 resource, including any S3-specific parameters.
     */
    // Use raw-path, otherwise escaped characters are unescaped and a wrong
    // signature is produced
    String xfullUrl = uri.getPath();
    String fullUrl = uri.getRawPath();

    // If we are using an alternative hostname, include the hostname/bucketname in the resource path.
    String s3Endpoint = this.getEndpoint();
    if (hostname != null && !s3Endpoint.equals(hostname)) {
        int subdomainOffset = hostname.lastIndexOf("." + s3Endpoint);
        if (subdomainOffset > 0) {
            // Hostname represents an S3 sub-domain, so the bucket's name is the CNAME portion
            fullUrl = "/" + hostname.substring(0, subdomainOffset) + fullUrl;
        } else {
            // Hostname represents a virtual host, so the bucket's name is identical to hostname
            fullUrl = "/" + hostname + fullUrl;
        }
    }

    String queryString = uri.getRawQuery();
    if (queryString != null && queryString.length() > 0) {
        fullUrl += "?" + queryString;
    }

    // Set/update the date timestamp to the current time
    // Note that this will be over-ridden if an "x-amz-date" or
    // "x-goog-date" header is present.
    httpMethod.setHeader("Date", ServiceUtils.formatRfc822Date(getCurrentTimeWithOffset()));

    if (log.isDebugEnabled()) {
        log.debug("For creating canonical string, using uri: " + fullUrl);
    }

    // Generate a canonical string representing the operation.
    String canonicalString = null;
    try {
        canonicalString = RestUtils.makeServiceCanonicalString(httpMethod.getMethod(), fullUrl,
                convertHeadersToMap(httpMethod.getAllHeaders()), null, getRestHeaderPrefix(),
                getResourceParameterNames());
    } catch (UnsupportedEncodingException e) {
        throw new RuntimeException(e.getMessage(), e);
    }
    if (log.isDebugEnabled()) {
        log.debug("Canonical string ('|' is a newline): " + canonicalString.replace('\n', '|'));
    }

    // Sign the canonical string.
    String signedCanonical = ServiceUtils.signWithHmacSha1(getProviderCredentials().getSecretKey(),
            canonicalString);

    // Add encoded authorization to connection as HTTP Authorization header.
    String authorizationString = getSignatureIdentifier() + " " + getProviderCredentials().getAccessKey() + ":"
            + signedCanonical;
    httpMethod.setHeader("Authorization", authorizationString);
}

From source file:org.jets3t.service.impl.rest.httpclient.RestStorageService.java

/**
 * Adds all valid metadata name and value pairs as HTTP headers to the given HTTP method.
 * Null metadata names are ignored, as are metadata values that are not of type string.
 * <p>//from w ww .  java2  s  .  c o  m
 * The metadata values are verified to ensure that keys contain only ASCII characters,
 * and that items are not accidentally duplicated due to use of different capitalization.
 * If either of these verification tests fails, an {@link org.jets3t.service.ServiceException} is thrown.
 *
 * @param httpMethod
 * @param metadata
 * @throws org.jets3t.service.ServiceException
 */
protected void addMetadataToHeaders(HttpUriRequest httpMethod, Map<String, Object> metadata)
        throws ServiceException {
    Map<String, Object> headersAlreadySeenMap = new HashMap<String, Object>(metadata.size());

    for (Map.Entry<String, Object> entry : metadata.entrySet()) {
        String key = entry.getKey();
        Object objValue = entry.getValue();

        if (key == null) {
            // Ignore invalid metadata.
            continue;
        }

        String value = objValue.toString();

        // Ensure user-supplied metadata values are compatible with the REST interface.
        // Key must be ASCII text, non-ASCII characters are not allowed in HTTP header names.
        boolean validAscii = false;
        UnsupportedEncodingException encodingException = null;
        try {
            byte[] asciiBytes = key.getBytes("ASCII");
            byte[] utf8Bytes = key.getBytes("UTF-8");
            validAscii = Arrays.equals(asciiBytes, utf8Bytes);
        } catch (UnsupportedEncodingException e) {
            // Shouldn't ever happen
            encodingException = e;
        }
        if (!validAscii) {
            String message = "User metadata name is incompatible with the S3 REST interface, "
                    + "only ASCII characters are allowed in HTTP headers: " + key;
            if (encodingException == null) {
                throw new ServiceException(message);
            } else {
                throw new ServiceException(message, encodingException);
            }
        }

        // Fail early if user-supplied metadata cannot be represented as valid HTTP headers,
        // rather than waiting for a SignatureDoesNotMatch error.
        // NOTE: These checks are very much incomplete.
        if (value.indexOf('\n') >= 0 || value.indexOf('\r') >= 0) {
            throw new ServiceException("The value of metadata item " + key
                    + " cannot be represented as an HTTP header for the REST S3 interface: " + value);
        }

        // Ensure each AMZ header is uniquely identified according to the lowercase name.
        String duplicateValue = (String) headersAlreadySeenMap.get(key.toLowerCase(Locale.US));
        if (duplicateValue != null && !duplicateValue.equals(value)) {
            throw new ServiceException(
                    "HTTP header name occurs multiple times in request with different values, "
                            + "probably due to mismatched capitalization when setting metadata names. "
                            + "Duplicate metadata name: '" + key + "', All metadata: " + metadata);
        }

        // PUT: don't set the 'Content-Length' header or http-client-4 will
        // raise an exception 'already set'.
        if (!httpMethod.getMethod().equalsIgnoreCase("PUT")
                || !SS3Object.METADATA_HEADER_CONTENT_LENGTH.equalsIgnoreCase(key)) {
            httpMethod.setHeader(key, value);
        }
        headersAlreadySeenMap.put(key.toLowerCase(Locale.US), value);
    }
}

From source file:net.tsz.afinal.http.HttpHandler.java

private void makeRequestWithRetries(HttpUriRequest request) throws IOException {
    if (isResume && targetUrl != null) {
        File downloadFile = new File(targetUrl);
        long fileLen = 0;
        if (downloadFile.isFile() && downloadFile.exists()) {
            fileLen = downloadFile.length();
        }/*from  w w w  . j a  v a2 s .c o  m*/
        if (fileLen > 0)
            request.setHeader("RANGE", "bytes=" + fileLen + "-");
    }

    boolean retry = true;
    IOException cause = null;
    HttpRequestRetryHandler retryHandler = client.getHttpRequestRetryHandler();//?
    while (retry) {
        try {
            if (isCancelled()) {
                return;
            }

            //POST:?;GET:?
            String requestUrl = request.getURI().toString();
            String requestMethod = request.getMethod();
            ZLogger.d(String.format("<%d><%s> %s", executionCount, requestMethod, requestUrl));

            for (Header header : request.getAllHeaders()) {
                ZLogger.d(String.format("<%s>:<%s>", header.getName(), header.getValue()));
            }

            //??url
            StringBuilder requestParams = new StringBuilder();
            if (requestMethod.equals(POST)) {
                HttpEntityEnclosingRequestBase requestBase = (HttpEntityEnclosingRequestBase) request;
                if (requestBase != null) {
                    HttpEntity entity = requestBase.getEntity();
                    if (entity != null) {
                        InputStream is = entity.getContent();
                        BufferedReader reader = new BufferedReader(new InputStreamReader(is));
                        String line = null;
                        try {
                            while ((line = reader.readLine()) != null) {
                                //                            sb.append(line + "/n");
                                //                                Log.d("Nat: makeRequestWithRetries.request.Params.line", line);
                                requestParams.append(line);
                            }
                        } catch (IOException e) {
                            e.printStackTrace();
                            ZLogger.ef(e.toString());
                        } finally {
                            try {
                                is.close();
                            } catch (IOException e) {
                                e.printStackTrace();
                            }
                        }
                    }
                    //                        byte[] paramsArray = EntityUtils.toByteArray(entity);
                    //                        String paramsStr = EntityUtils.toString(entity, "UTF-8");
                    //                        Log.d("Nat: makeRequestWithRetries.request.Params(2)", paramsStr);
                    //                        Log.d("Nat: makeRequestWithRetries.request.Params(3)", EntityUtils.toString(entity));
                }

                //                    Log.d("Nat: makeRequestWithRetries.request.Params(RAW)", requestParams.toString());
            }

            //
            HttpResponse response = client.execute(request, context);
            //                for(Header header : response.getAllHeaders()){
            //                    Log.d("Nat", String.format(" makeRequestWithRetries.respoonse.header <%s><%s>", header.getName(), header.getValue()));
            //                }

            if (isCancelled()) {
                ZLogger.d("Nat: makeRequestWithRetries", "request caneled.");
                return;
            }

            //POST:?;GET:?
            request.getRequestLine();//GET
            ZLogger.d(request.getRequestLine().toString());
            /*if (request.getMethod().equals("post")) {
            HttpParams params = request.getParams();
             params.setParameter(NetFactory.CLIENTSESSION, "");
            request.snetParams(params);
            }*/

            //?????()
            //executionCount < 1,?????
            if (response.containsHeader("needLogin")/* && executionCount < 1*/) {
                //?url?JSSIONID??cookie.
                //?(?),sessionId
                String newSid = MfhLoginService.get().doLogin();
                if (newSid == null) {
                    //TODO
                    //,?
                    //                        Intent intent = new Intent(Constants.ACTION_REDIRECT_TO_LOGIN_H5);
                    //                        BizApplication.getAppContext().sendBroadcast(intent);
                    //                        break;
                } else {
                    String cookie = String.format("%s=%s", FinalHttp.KEY_JSESSIONID, newSid);
                    request.addHeader(FinalHttp.HEADER_SET_COOKIE, cookie);
                    request.addHeader(FinalHttp.HEADER_COOKIE, cookie);
                    request.addHeader(FinalHttp.HEADER_cookie, cookie);
                    // ?
                    //                        MsgBridgeUtil.register();

                    if (requestMethod.equals(POST)) {
                        //                        //EntityJSSIONID
                        String newParams = replaceParam(requestParams.toString(), JSESSIONID, newSid);
                        //                            HttpEntity entity = new StringEntity(newParams);
                        HttpEntity entity = convertToAjaxParams(newParams).getEntity();
                        ((HttpEntityEnclosingRequestBase) request).setEntity(entity);
                    } else if (requestMethod.equals(GET)) {
                        //URLJSSIONID
                        String newRequestUrl = replaceParam(requestUrl, JSESSIONID, newSid);
                        //                            newRequestUrl = replaceParam(newRequestUrl, "lastupdate", "0");
                        URI uri = new URI(newRequestUrl);
                        //                            Log.d("Nat: makeRequestWithRetries.autoLogin.URI", uri.toString());
                        //                                HttpEntityEnclosingRequestBase requestFact = (HttpEntityEnclosingRequestBase)request;
                        //                                requestFact.setURI(uri);
                        ((HttpEntityEnclosingRequestBase) request).setURI(uri);
                    }
                }

                //TODO,?
                retry = (++executionCount <= MAX_RETRY_TIMES)
                        || retryHandler.retryRequest(new IOException("Exception"), executionCount, context);
                //                    ZLogger.d(String.format("%s  %d", retry ? "?" : "??", executionCount));
                if (retry) {
                    continue;
                }
            }

            //?
            handleResponse(response);
            return;
        } catch (UnknownHostException e) {
            ZLogger.e("UnknownHostException:" + e.toString());
            publishProgress(UPDATE_FAILURE, e, "unknownHostExceptioncan't resolve host");
            return;
        } catch (IOException e) {
            ZLogger.e("IOException: " + e.toString());
            cause = e;
            retry = retryHandler.retryRequest(cause, ++executionCount, context);
            publishProgress(UPDATE_FAILURE, e, "unknownHostExceptioncan't resolve host");
        } catch (NullPointerException e) {
            if (e != null) {
                ZLogger.e("NullPointerException: " + e.toString());
                // here's a bug in HttpClient 4.0.x that on some occasions causes
                // DefaultRequestExecutor to throw an NPE, see
                // http://code.google.com/p/android/issues/detail?id=5255
                cause = new IOException("NPE in HttpClient: " + e.getMessage());
                retry = retryHandler.retryRequest(cause, ++executionCount, context);
            } else {
                ZLogger.e("NullPointerException: e is null");
            }
            publishProgress(UPDATE_FAILURE, e, "unknownHostExceptioncan't resolve host");
        } catch (Exception e) {
            ZLogger.e("Exception: " + e.toString());
            cause = new IOException("Unhandled Exception" + e.getMessage());
            retry = retryHandler.retryRequest(cause, ++executionCount, context);
            publishProgress(UPDATE_FAILURE, e, "unknownHostExceptioncan't resolve host");
        }
    }

    // cleaned up to throw IOException
    if (cause != null) {
        throw cause;
    }
    //        else{
    //            //TODO
    //            throw new IOException("");
    //        }
}

From source file:org.fcrepo.client.utils.HttpHelper.java

/**
 * Execute a request for a subclass./*from  w w w. j  a v a  2s.c o  m*/
 *
 * @param request request to be executed
 * @return response containing response to request
 * @throws IOException
 * @throws ReadOnlyException
**/
public HttpResponse execute(final HttpUriRequest request) throws IOException, ReadOnlyException {
    if (readOnly) {
        switch (request.getMethod().toLowerCase()) {
        case "copy":
        case "delete":
        case "move":
        case "patch":
        case "post":
        case "put":
            throw new ReadOnlyException();
        default:
            break;
        }
    }

    return httpClient.execute(request, httpContext);
}

From source file:org.opencastproject.kernel.security.TrustedHttpClientImpl.java

@Override
public HttpResponse execute(HttpUriRequest httpUriRequest, int connectionTimeout, int socketTimeout)
        throws TrustedHttpClientException {
    HttpClient httpClient = makeHttpClient();
    httpClient.getParams().setIntParameter(CoreConnectionPNames.CONNECTION_TIMEOUT, connectionTimeout);
    // Add the request header to elicit a digest auth response
    httpUriRequest.setHeader(REQUESTED_AUTH_HEADER, DIGEST_AUTH);
    httpUriRequest.setHeader(SecurityConstants.AUTHORIZATION_HEADER, "true");

    if (serviceRegistry != null && serviceRegistry.getCurrentJob() != null)
        httpUriRequest.setHeader(CURRENT_JOB_HEADER, Long.toString(serviceRegistry.getCurrentJob().getId()));

    // If a security service has been set, use it to pass the current security context on
    logger.debug("Adding security context to request");
    Organization organization = securityService.getOrganization();
    if (organization != null) {
        httpUriRequest.setHeader(SecurityConstants.ORGANIZATION_HEADER, organization.getId());
        User currentUser = securityService.getUser();
        if (currentUser != null)
            httpUriRequest.setHeader(SecurityConstants.USER_HEADER, currentUser.getUserName());
    }//from w ww.j a v  a 2 s  .  c  om

    if ("GET".equalsIgnoreCase(httpUriRequest.getMethod())
            || "HEAD".equalsIgnoreCase(httpUriRequest.getMethod())) {
        // Set the user/pass
        UsernamePasswordCredentials creds = new UsernamePasswordCredentials(user, pass);
        httpClient.getCredentialsProvider().setCredentials(AuthScope.ANY, creds);

        // Run the request (the http client handles the multiple back-and-forth requests)
        HttpResponse response = null;
        try {
            response = httpClient.execute(httpUriRequest);
            responseMap.put(response, httpClient);
            return response;
        } catch (IOException e) {
            // close the http connection(s)
            httpClient.getConnectionManager().shutdown();
            throw new TrustedHttpClientException(e);
        }
    }

    // HttpClient doesn't handle the request dynamics for other verbs (especially when sending a streamed multipart
    // request), so we need to handle the details of the digest auth back-and-forth manually
    manuallyHandleDigestAuthentication(httpUriRequest, httpClient);

    HttpResponse response = null;
    try {
        response = httpClient.execute(httpUriRequest);
        if (nonceTimeoutRetries > 0 && hadNonceTimeoutResponse(response)) {
            httpClient.getConnectionManager().shutdown();
            response = retryAuthAndRequestAfterNonceTimeout(httpUriRequest, response);
        }
        responseMap.put(response, httpClient);
        return response;
    } catch (Exception e) {
        // if we have a response, remove it from the map
        if (response != null) {
            responseMap.remove(response);
        }
        // close the http connection(s)
        httpClient.getConnectionManager().shutdown();
        throw new TrustedHttpClientException(e);
    }
}

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

protected CloseableHttpResponse execute(final HttpUriRequest request) throws IOException, B2ApiException {
    this.setHeaders(request);
    LOGGER.debug("{} request to URL '{}'", request.getMethod(), request.getURI());
    final CloseableHttpResponse httpResponse = client.execute(request);
    if (LOGGER.isDebugEnabled()) {
        LOGGER.debug("Received status code of: {}, for {} request to url '{}'",
                httpResponse.getStatusLine().getStatusCode(), request.getMethod(), request.getURI());
    }/*from   ww  w. j  a  v  a 2  s.co  m*/
    return httpResponse;
}