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

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

Introduction

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

Prototype

public Header[] getAllHeaders() 

Source Link

Usage

From source file:lucee.runtime.tag.Http.java

private static boolean hasHeaderIgnoreCase(HttpRequestBase req, String name) {
    org.apache.http.Header[] headers = req.getAllHeaders();
    if (headers == null)
        return false;
    for (int i = 0; i < headers.length; i++) {
        if (name.equalsIgnoreCase(headers[i].getName()))
            return true;
    }//from w ww . ja  v a 2  s. c  o m
    return false;
}

From source file:com.magnet.plugin.api.requests.abs.BaseRequest.java

@Override
public void doWork() {
    try {/*from  ww w . ja  va  2s.  c  o  m*/
        HttpClient httpClient = HttpClientBuilder.create().build();
        HttpRequestBase request = getRequest(requestModel);

        List<RequestHeaderModel> requestModelHeaders = requestModel.getHeaders();

        for (RequestHeaderModel header : requestModelHeaders) {
            request.setHeader(header.getName(), header.getValue());
        }

        // If not specified as a header argument, Content-Type is inferred from the request body
        // Add the header here so the request is successful.
        if (request.getHeaders(ContentTypeHelper.CONTENT_TYPE_HEADER) == null
                || request.getHeaders(ContentTypeHelper.CONTENT_TYPE_HEADER).length == 0) {
            RestContentType type = ExampleParser.guessContentType(requestModel.getRequest());
            if (null != type) {
                request.setHeader(ContentTypeHelper.CONTENT_TYPE_HEADER, type.getName());
            }
        }
        // check if content-type is parameterized
        HttpResponse httpResponse = httpClient.execute(request);
        ApiMethodModel methodModel = new ApiMethodModel();
        methodModel.setRequestHeaders(request.getAllHeaders());
        methodModel.setHttpResponse(httpResponse);
        methodModel.setRequestModel(requestModel);
        onSuccess(methodModel);
    } catch (Exception e) {
        e.printStackTrace();
        Logger.info(getClass(), e.toString());
        onError(e);
    }

}

From source file:javax.microedition.ims.core.xdm.XDMServiceImpl.java

private void printRequest(HttpRequestBase httpRequest) {
    Logger.log(TAG, "------------------------------ Request Begin ------------------------------");
    Logger.log(TAG, httpRequest.getRequestLine().toString());

    for (Header header : httpRequest.getAllHeaders()) {
        Logger.log(TAG, header.getName() + " = " + header.getValue());
    }//from   w  ww.  ja v a  2s . com
    Logger.log(TAG, "------------------------------ Request End ------------------------------");
}

From source file:com.aol.webservice_base.util.http.HttpHelper.java

/**
 * Http client call./*from   w  ww  .  j av  a 2s.c  o m*/
 *
 * callers to this are responsible for ensuring connection is closed properly - httpHelper.releaseResponse() 
 *
 * @param requestMethod the request method
 * @param url the url
 * @param headers the headers
 * @param content the content
 * @return the http response
 * @throws HttpException the http exception
 */
protected HttpResponse httpClientCall(String requestMethod, String url, Map<String, String> headers,
        Object content) throws HttpException {
    HttpResponse response = null;
    if (!inited) {
        throw new Error("HttpHelper used when not initialized (call init) for " + url);
    }

    final String METHOD = "HttpHelper.httpClientCall()";
    HttpRequestBase httpRequest = null;
    boolean success = false;

    int iter = 0;
    int status;
    String statusMsg;
    do {
        try {
            long begin = System.currentTimeMillis();
            new URL(url);
            httpRequest = getHttpRequest(requestMethod, url, content);

            if (headers != null && headers.size() > 0) {
                for (Map.Entry<String, String> headerSet : headers.entrySet()) {
                    httpRequest.addHeader(headerSet.getKey(), headerSet.getValue());
                }
            }
            Header[] requestHeaders = httpRequest.getAllHeaders();
            for (int i = 0; i < requestHeaders.length; i++) {
                String name = requestHeaders[i].getName();
                String value = requestHeaders[i].getValue();
                if (logger.isDebugEnabled()) {
                    logger.debug("Request header " + name + " = [" + value + "]");
                }
            }

            // make the request
            //httpRequest.setFollowRedirects(false);
            response = httpClient.execute(httpRequest);
            status = response.getStatusLine().getStatusCode();
            statusMsg = response.getStatusLine().getReasonPhrase();
            if (logger.isDebugEnabled()) {
                logger.debug(METHOD + " status=" + status + " status desc: [" + statusMsg + "] url=[" + url
                        + "] took=" + (System.currentTimeMillis() - begin) + " ms");
            }
            if (status == 302 || status == 301) {
                Header loc = httpRequest.getFirstHeader("Location");
                if (loc != null) {
                    String origUrl = url;
                    url = loc.getValue();
                    if (!url.startsWith("http")) {
                        url = addHost(origUrl, url);
                    }
                    continue;
                }
            }
            if (status != 200 /* && status != 304 */) {
                throw new HttpException(status, statusMsg);
            }

            if (logger.isDebugEnabled()) {
                Header[] responseHeaders = response.getAllHeaders();
                for (int i = 0; i < responseHeaders.length; i++) {
                    String name = responseHeaders[i].getName();
                    String value = responseHeaders[i].getValue();
                    logger.debug("Response header " + name + " = [" + value + "]");
                }
            }

            success = true;
            return response;
        } catch (MalformedURLException e) {
            String msg = "target URL = [" + url + "] is invalid.";
            logger.error(msg);
            throw new HttpException(HttpServletResponse.SC_NOT_FOUND, msg);
        } catch (HttpException e) {
            logger.error("HttpException " + METHOD + " url=" + url + " exception=" + e.getMessage());
            throw e;
        } catch (java.net.SocketTimeoutException e) {
            logger.error("SocketTimeoutException " + METHOD + " url=" + url + " exception=" + e.getMessage());
            throw new HttpException(HttpServletResponse.SC_GATEWAY_TIMEOUT,
                    "Connection or Read timeout exception: " + e);
        } catch (Throwable t) {
            logger.error("HttpException " + METHOD + " url=" + url + " exception=" + t.getMessage());
            throw new HttpException(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, t);
        } finally {
            // release the connection whenever we are not successful
            if ((!success) && (response != null)) {
                try {
                    releaseResponse(response);
                    response = null;
                } catch (IOException e) {
                    logger.error("HttpHelper - problem releasing connection", e);
                }
            }
        }
    } while (!success && (++iter <= this.followRedirectMax));

    throw new HttpException(status, statusMsg);
}

From source file:com.xively.client.http.DefaultRequestHandler.java

private <T extends DomainObject> HttpRequestBase buildRequest(HttpMethod requestMethod, String appPath,
        Map<String, Object> params, T... bodyObjects) {
    AcceptedMediaType mediaType = AppConfig.getInstance().getResponseMediaType();

    HttpRequestBase request = null;
    switch (requestMethod) {
    case DELETE://w  w  w. jav a  2  s . com
        request = new HttpDelete();
        break;

    case GET:
        request = new HttpGet();
        break;

    case POST:
        request = new HttpPost();
        StringEntity postEntity = getEntity(false, bodyObjects);
        ((HttpPost) request).setEntity(postEntity);
        break;

    case PUT:
        request = new HttpPut();
        StringEntity putEntity = getEntity(true, bodyObjects);
        ((HttpPut) request).setEntity(putEntity);
        break;

    default:
        return null;
    }

    URIBuilder uriBuilder = buildUri(requestMethod, appPath, params, mediaType);
    try {
        request.setURI(uriBuilder.build());
    } catch (URISyntaxException e) {
        throw new RequestInvalidException("Invalid URI requested.", e);
    }

    request.addHeader("accept", mediaType.getMediaType());
    request.addHeader(HEADER_KEY_API, AppConfig.getInstance().getApiKey());
    request.addHeader(HEADER_USER_AGENT, XIVELY_USER_AGENT);

    if (log.isDebugEnabled()) {
        StringBuilder sb = new StringBuilder();
        for (Header header : request.getAllHeaders()) {
            sb.append(header.getName()).append(",").append(header.getValue()).append(";");
        }
        log.debug(String.format("Constructed request with uri [%s], header [%s]", uriBuilder.toString(),
                sb.toString()));
    }

    return request;
}

From source file:org.dasein.cloud.atmos.AtmosMethod.java

protected void authorize(@Nonnull ProviderContext ctx, @Nonnull HttpRequestBase method,
        @Nonnull String contentType, @Nullable String range) throws CloudException, InternalException {
    ArrayList<Header> emcHeaders = new ArrayList<Header>();
    String date = provider.formatTime(System.currentTimeMillis());

    try {/* www .  j a  v a  2s .  com*/
        method.addHeader("x-emc-uid",
                new String(ctx.getAccessPublic(), "utf-8") + "/" + ctx.getAccountNumber());
    } catch (UnsupportedEncodingException e) {
        logger.error("UTF-8 error: " + e.getMessage());
        throw new InternalException(e);
    }
    method.addHeader("Date", date);

    for (Header h : method.getAllHeaders()) {
        if (h.getName().toLowerCase().startsWith("x-emc")) {
            emcHeaders.add(h);
        }
    }
    String signatureString = toSignatureString(method, contentType, range == null ? "" : range, date,
            method.getURI(), emcHeaders);
    logger.debug(signatureString);
    String signature = sign(ctx, signatureString);
    logger.debug(signature);
    method.addHeader("x-emc-signature", signature);
}

From source file:org.dasein.cloud.aws.storage.GlacierMethod.java

private ClientAndResponse invokeInternal() throws InternalException, CloudException {

    if (wire.isDebugEnabled()) {
        wire.debug("");
        wire.debug("----------------------------------------------------------------------------------");
    }//from www .  ja  v  a  2s.co  m
    try {
        final String url = getUrlWithParameters();
        final String host;
        try {
            host = new URI(url).getHost();
        } catch (URISyntaxException e) {
            throw new InternalException(e);
        }
        final HttpRequestBase method = action.getMethod(url);

        final HttpClient client = provider.getClient();

        final String accessId;
        final String secret;
        try {
            accessId = new String(provider.getContext().getAccessPublic(), "utf-8");
            secret = new String(provider.getContext().getAccessPrivate(), "utf-8");
        } catch (UnsupportedEncodingException e) {
            throw new InternalException(e);
        }
        headers.put(AWSCloud.P_AWS_DATE, provider.getV4HeaderDate(null));
        headers.put("x-amz-glacier-version", API_VERSION);
        headers.put("host", host);
        final String v4Authorization = provider.getV4Authorization(accessId, secret, method.getMethod(), url,
                SERVICE_ID, headers, getRequestBodyHash());
        for (Map.Entry<String, String> entry : headers.entrySet()) {
            method.addHeader(entry.getKey(), entry.getValue());
        }
        method.addHeader(AWSCloud.P_CFAUTH, v4Authorization);

        if (bodyText != null) {
            try {
                ((HttpEntityEnclosingRequestBase) method).setEntity(new StringEntity(bodyText));
            } catch (UnsupportedEncodingException e) {
                throw new InternalException(e);
            }
        }

        if (wire.isDebugEnabled()) {
            wire.debug("[" + url + "]");
            wire.debug(method.getRequestLine().toString());
            for (Header header : method.getAllHeaders()) {
                wire.debug(header.getName() + ": " + header.getValue());
            }
            wire.debug("");
            if (bodyText != null) {
                try {
                    wire.debug(EntityUtils.toString(((HttpEntityEnclosingRequestBase) method).getEntity()));
                } catch (IOException ignore) {
                }

                wire.debug("");
            }
        }

        HttpResponse httpResponse;
        try {
            httpResponse = client.execute(method);
        } catch (IOException e) {
            throw new CloudException(e);
        }
        if (wire.isDebugEnabled()) {
            wire.debug(httpResponse.getStatusLine().toString());
            for (Header header : httpResponse.getAllHeaders()) {
                wire.debug(header.getName() + ": " + header.getValue());
            }
            wire.debug("");
        }

        int status = httpResponse.getStatusLine().getStatusCode();
        if (status >= 400) {
            throw getGlacierException(httpResponse);
        } else {
            return new ClientAndResponse(client, httpResponse);
        }
    } finally {
        if (wire.isDebugEnabled()) {
            wire.debug("----------------------------------------------------------------------------------");
            wire.debug("");
        }
    }
}

From source file:org.hardisonbrewing.s3j.FileSyncer.java

private String signature(String accessKey, long expires, String resource, HttpRequestBase request)
        throws Exception {

    StringBuffer stringBuffer = new StringBuffer();

    // HTTP-VERB//from w  ww.j a  v  a  2 s.  co  m
    stringBuffer.append(request.getMethod());
    stringBuffer.append("\n");

    // Content-MD5
    //        if ( !( request instanceof HttpEntityEnclosingRequestBase ) ) {
    stringBuffer.append("\n");
    //        }
    //        else {
    //            HttpEntityEnclosingRequestBase entityRequest = (HttpEntityEnclosingRequestBase) request;
    //            HttpEntity entity = entityRequest.getEntity();
    //            stringBuffer.append( md5( IOUtil.toByteArray( entity.getContent() ) ) );
    //            stringBuffer.append( "\n" );
    //        }

    //Content-Type
    //        if ( !( request instanceof HttpEntityEnclosingRequestBase ) ) {
    stringBuffer.append("\n");
    //        }
    //        else {
    //            HttpEntityEnclosingRequestBase entityRequest = (HttpEntityEnclosingRequestBase) request;
    //            HttpEntity entity = entityRequest.getEntity();
    //            stringBuffer.append( entity.getContentType().getValue() );
    //            stringBuffer.append( "\n" );
    //        }

    // Expires
    boolean hasAmzDateHeader = request.getLastHeader("x-amz-date") != null;
    stringBuffer.append(hasAmzDateHeader ? "" : expires);
    stringBuffer.append("\n");

    // CanonicalizedAmzHeaders
    for (Header header : request.getAllHeaders()) {
        String name = header.getName();
        if (name.startsWith("x-amz")) {
            stringBuffer.append(name);
            stringBuffer.append(":");
            stringBuffer.append(header.getValue());
            stringBuffer.append("\n");
        }
    }

    stringBuffer.append(resource); // CanonicalizedResource

    String signature = stringBuffer.toString();
    byte[] bytes = signature.getBytes("UTF-8");
    bytes = hmacSHA1(accessKey, bytes);
    signature = Base64.encodeBase64String(bytes);
    return signature;
}