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

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

Introduction

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

Prototype

public void addHeader(String str, String str2) 

Source Link

Usage

From source file:io.kyligence.benchmark.loadtest.client.RestClient.java

private void addHttpHeaders(HttpRequestBase method) {
    method.addHeader("Accept", "application/json, text/plain, */*");
    method.addHeader("Content-Type", "application/json");
    String basicAuth = DatatypeConverter.printBase64Binary((this.userName + ":" + this.password).getBytes());
    method.addHeader("Authorization", "Basic " + basicAuth);
}

From source file:net.sourcewalker.garanbot.api.GaranboClient.java

private void prepareRequest(String contentType, HttpRequestBase request, Header[] additionalHeaders) {
    request.addHeader("Content-type", contentType);
    request.addHeader("open-api", ApiConstants.KEY);
    request.addHeader("Authorization", getAuthHeader());
    for (Header h : additionalHeaders) {
        request.addHeader(h);/*from  w  ww.ja va2  s .co m*/
    }
}

From source file:com.emc.storageos.driver.dellsc.scapi.rest.RestClient.java

/**
 * Execute a REST call./*  w w w.  j  a  v a  2  s  . co m*/
 *
 * @param request The REST request.
 * @return The results from the execution.
 */
private RestResult executeRequest(HttpRequestBase request) {
    RestResult result = null;

    request.addHeader("Accept", "application/json");
    request.addHeader("x-dell-api-version", "2.0");
    request.addHeader("Content-Type", "application/json; charset=utf-8");

    CloseableHttpResponse response = null;
    try {
        response = httpClient.execute(request, httpContext);
        HttpEntity entity = response.getEntity();
        result = new RestResult(request.getURI().toString(), response.getStatusLine().getStatusCode(),
                response.getStatusLine().getReasonPhrase(),
                entity != null ? EntityUtils.toString(response.getEntity()) : "");
    } catch (IOException e) {
        result = new RestResult(500, "Internal Failure", "");
        LOG.warn(String.format("Error in API request: %s", e), e);
    } finally {
        try {
            if (response != null) {
                response.close();
            }
        } catch (IOException e) {
        }
    }

    return result;
}

From source file:org.mocksy.rules.http.HttpProxyRule.java

protected HttpRequestBase getProxyMethod(HttpServletRequest request) {
    String proxyUrl = this.proxyUrl;
    proxyUrl += request.getPathInfo();/*w w w.  j a va 2  s.c  o  m*/
    if (request.getQueryString() != null) {
        proxyUrl += "?" + request.getQueryString();
    }
    HttpRequestBase method = null;
    if ("GET".equals(request.getMethod())) {
        method = new HttpGet(proxyUrl);
        method.addHeader("Cache-Control", "no-cache");
        method.addHeader("Pragma", "no-cache");
    } else if ("POST".equals(request.getMethod())) {
        method = new HttpPost(proxyUrl);

        Map<String, String[]> paramMap = request.getParameterMap();
        List<NameValuePair> params = new ArrayList<NameValuePair>();
        for (String paramName : paramMap.keySet()) {
            String[] values = paramMap.get(paramName);
            for (String value : values) {
                NameValuePair param = new BasicNameValuePair(paramName, value);
                params.add(param);
            }
        }

        try {
            ((HttpPost) method).setEntity(new UrlEncodedFormEntity(params));
        } catch (UnsupportedEncodingException e) {
            // don't worry, this won't happen
        }
    }

    Enumeration headers = request.getHeaderNames();
    while (headers.hasMoreElements()) {
        String header = (String) headers.nextElement();
        if ("If-Modified-Since".equals(header) || "Content-Length".equals(header)
                || "Transfer-Encoding".equals(header))
            continue;
        Enumeration values = request.getHeaders(header);
        while (values.hasMoreElements()) {
            String value = (String) values.nextElement();
            method.addHeader(header, value);
        }
    }

    return method;
}

From source file:com.mgmtp.perfload.core.client.web.http.DefaultHttpClientManager.java

/**
 * Executes an HTTP request using the internal {@link HttpClient} instance encapsulating the
 * Http response in the returns {@link ResponseInfo} object. This method takes to time
 * measurements around the request execution, one after calling
 * {@link HttpClient#execute(org.apache.http.client.methods.HttpUriRequest, HttpContext)} (~
 * first-byte measurment) and the other one later after the complete response was read from the
 * stream. These measurements are return as properties of the {@link ResponseInfo} object.
 *///from   ww  w. ja  va 2  s  .c om
@Override
public ResponseInfo executeRequest(final HttpRequestBase request, final HttpContext context,
        final UUID requestId) throws IOException {
    request.addHeader(EXECUTION_ID_HEADER, executionId.toString());
    request.addHeader(OPERATION_HEADER, operation);
    request.addHeader(REQUEST_ID_HEADER, requestId.toString());

    String uri = request.getURI().toString();
    String type = request.getMethod();

    TimeInterval tiBeforeBody = new TimeInterval();
    TimeInterval tiTotal = new TimeInterval();

    tiBeforeBody.start();
    tiTotal.start();
    long timestamp = System.currentTimeMillis();

    HttpResponse response = getHttpClient().execute(request, context);
    tiBeforeBody.stop();

    // This actually downloads the response body:
    HttpEntity entity = response.getEntity();
    byte[] body = EntityUtils.toByteArray(entity);
    tiTotal.stop();

    StatusLine statusLine = response.getStatusLine();
    int statusCode = statusLine.getStatusCode();
    String statusMsg = statusLine.getReasonPhrase();
    String responseCharset = EntityUtils.getContentCharSet(entity);
    String contentType = EntityUtils.getContentMimeType(entity);
    String bodyAsString = bodyAsString(contentType, responseCharset, body);

    Header[] headers = response.getAllHeaders();
    Map<String, String> responseHeaders = newHashMapWithExpectedSize(headers.length);
    for (Header header : headers) {
        responseHeaders.put(header.getName(), header.getValue());
    }

    return new ResponseInfo(type, uri, statusCode, statusMsg, responseHeaders, body, bodyAsString,
            responseCharset, contentType, timestamp, tiBeforeBody, tiTotal, executionId, requestId);
}

From source file:org.apache.gobblin.source.extractor.extract.restapi.RestApiConnector.java

protected void addHeaders(HttpRequestBase httpRequest) {
    if (this.accessToken != null) {
        httpRequest.addHeader("Authorization", "OAuth " + this.accessToken);
    }//from   w  ww  .jav a  2s  . c o m
    httpRequest.addHeader("Content-Type", "application/json");
    //httpRequest.addHeader("Accept-Encoding", "zip");
    //httpRequest.addHeader("Content-Encoding", "gzip");
    //httpRequest.addHeader("Connection", "Keep-Alive");
    //httpRequest.addHeader("Keep-Alive", "timeout=60000");
}

From source file:org.wso2.carbon.identity.cloud.web.jaggery.clients.MutualSSLHttpClient.java

private String doHttpMethod(HttpRequestBase httpMethod, HttpHeaders headers) {
    String responseString = null;
    try {//from w  w w  .  j  a v  a 2  s  . c  om
        for (Map.Entry<String, String> entry : headers.getHeaderMap().entrySet()) {
            httpMethod.addHeader(entry.getKey(), entry.getValue());
        }

        HttpResponse closeableHttpResponse = httpClient.execute(httpMethod);
        HttpEntity entity = closeableHttpResponse.getEntity();
        responseString = EntityUtils.toString(entity, "UTF-8");
    } catch (IOException e) {
        log.error("Error while executing the http method " + httpMethod.getMethod() + ". Endpoint : "
                + httpMethod.getURI(), e);
    }
    return responseString;
}

From source file:com.socrata.ApiBase.java

/**
 * Performs a generic request against Socrata API servers
 * @param request Apache HttpRequest object (e.g. HttpPost, HttpGet)
 * @return JSON array representation of the response
 *///  w  w w .  j  av a  2 s .c  om
protected JsonPayload performRequest(HttpRequestBase request) {
    HttpResponse response;
    HttpEntity entity;

    request.addHeader("X-App-Token", this.appToken);
    try {
        response = httpClient.execute(httpHost, request, httpContext);

        if (response.getStatusLine().getStatusCode() != 200) {
            log(java.util.logging.Level.SEVERE, "Got status " + response.getStatusLine().getStatusCode() + ": "
                    + response.getStatusLine().toString() + " while performing request on " + request.getURI(),
                    null);
            return null;
        }

        return new JsonPayload(response);
    } catch (Exception ex) {
        log(Level.SEVERE, "Error caught trying to perform HTTP request", ex);
        return null;
    }
}

From source file:org.nextlets.erc.defaults.http.ERCHttpInvokerImpl.java

protected void addHeaders(HttpRequestBase req, Map<String, String> headers) {
    for (Entry<String, String> hdr : headers.entrySet()) {
        req.addHeader(hdr.getKey(), hdr.getValue());
    }/*  w ww  .java  2 s.  c  om*/
}

From source file:net.sf.jaceko.mock.it.helper.request.HttpRequestSender.java

private MockResponse executeRequest(HttpRequestBase httpRequest, boolean binary, Map<String, String> headers)
        throws IOException {
    for (String headerName : headers.keySet()) {
        httpRequest.addHeader(headerName, headers.get(headerName));
    }//from   w  w  w.  j a va  2 s  .  com
    return executeRequest(httpRequest, binary);
}