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:org.apache.manifoldcf.crawler.connectors.confluence.ConfluenceSession.java

/**
 * Get rest response and fill the query results
 * // w ww  .  ja va  2 s .c  o m
 * @param rightside
 * @param response
 * @throws IOException
 * @throws ResponseException
 */
public void getRest(String rightside, ConfluenceJSONResponse response) throws IOException, ResponseException {

    // Create AuthCache instance
    AuthCache authCache = new BasicAuthCache();
    // Generate BASIC scheme object and add it to the local
    // auth cache
    BasicScheme basicAuth = new BasicScheme();

    authCache.put(host, basicAuth);

    // Add AuthCache to the execution context
    HttpClientContext localContext = HttpClientContext.create();
    localContext.setAuthCache(authCache);

    String executionUrl = host.toURI() + path + (path.endsWith("/") ? "" : "/") + rightside;
    if (Logging.connectors != null)
        Logging.connectors.info("Execution url is :" + executionUrl);
    final HttpRequestBase method = new HttpGet(executionUrl);
    method.addHeader("Accept", "application/json");

    try {
        HttpResponse httpResponse = httpClient.execute(method, localContext);

        int resultCode = httpResponse.getStatusLine().getStatusCode();
        if (resultCode == 200) {
            // Logging.connectors.info("Successfully retrived response");
            Object jo = convertToJSON(httpResponse);
            response.acceptJSONObject(jo);
        } else if (resultCode == 401) {
            throw new IOException("There is Authentication failure, this may be due to capcha : "
                    + convertToString(httpResponse));
        } else {
            throw new IOException(
                    "Unexpected result code " + resultCode + ": " + convertToString(httpResponse));
        }

    } finally {
        method.abort();
    }
}

From source file:com.flipkart.poseidon.handlers.http.impl.HttpConnectionPool.java

/** Getter/Setter methods */
private void setRequestHeaders(HttpRequestBase request, Map<String, String> headers) {
    Map<String, String> requestHeaders = getRequestHeaders(headers);
    for (String key : requestHeaders.keySet()) {
        request.addHeader(key, requestHeaders.get(key));
    }//from   w  ww .j  a  v  a2 s . c om
}

From source file:org.herrlado.engeo.Utils.java

/**
 * Get a fresh HTTP-Connection.//from  w  ww . j a  v  a 2s  .  co m
 * 
 * @param url
 *            URL to open
 * @param cookies
 *            cookies to transmit
 * @param postData
 *            post data
 * @param userAgent
 *            user agent
 * @param referer
 *            referer
 * @param encoding
 *            encoding; default encoding: ISO-8859-15
 * @param trustAll
 *            trust all SSL certificates; only used on first call!
 * @param knownFingerprints
 *            fingerprints that are known to be valid; only used on first
 *            call! Only used if {@code trustAll == false}
 * @return the connection
 * @throws IOException
 *             IOException
 */
private static HttpResponse getHttpClient(final String url, final ArrayList<Cookie> cookies,
        final ArrayList<BasicNameValuePair> postData, final String userAgent, final String referer,
        final String encoding, final boolean trustAll, final String... knownFingerprints) throws IOException {
    Log.d(TAG, "HTTPClient URL: " + url);

    SchemeRegistry registry = null;
    if (httpClient == null) {
        if (trustAll || (// .
        knownFingerprints != null && // .
                knownFingerprints.length > 0)) {
            registry = new SchemeRegistry();
            registry.register(new Scheme("http", new PlainSocketFactory(), PORT_HTTP));
            // final FakeSocketFactory httpsSocketFactory;
            // if (trustAll) {
            // httpsSocketFactory = new FakeSocketFactory();
            // } else {
            // httpsSocketFactory = new FakeSocketFactory(
            // knownFingerprints);
            // }
            // registry.register(new Scheme("https", httpsSocketFactory,
            // PORT_HTTPS));
            HttpParams params = new BasicHttpParams();
            httpClient = new DefaultHttpClient(new ThreadSafeClientConnManager(params, registry), params);
        } else {
            httpClient = new DefaultHttpClient();
        }
        httpClient.addResponseInterceptor(new HttpResponseInterceptor() {
            @Override
            public void process(final HttpResponse response, final HttpContext context)
                    throws HttpException, IOException {
                HttpEntity entity = response.getEntity();
                Header contentEncodingHeader = entity.getContentEncoding();
                if (contentEncodingHeader != null) {
                    HeaderElement[] codecs = contentEncodingHeader.getElements();
                    for (int i = 0; i < codecs.length; i++) {
                        if (codecs[i].getName().equalsIgnoreCase(GZIP)) {
                            response.setEntity(new GzipDecompressingEntity(response.getEntity()));
                            return;
                        }
                    }
                }
            }
        });
    }
    if (cookies != null && cookies.size() > 0) {
        final int l = cookies.size();
        CookieStore cs = httpClient.getCookieStore();
        for (int i = 0; i < l; i++) {
            cs.addCookie(cookies.get(i));
        }
    }
    Log.d(TAG, getCookies(httpClient));

    HttpRequestBase request;
    if (postData == null) {
        request = new HttpGet(url);
    } else {
        HttpPost pr = new HttpPost(url);
        if (encoding != null && encoding.length() > 0) {
            pr.setEntity(new UrlEncodedFormEntity(postData, encoding));
        } else {
            pr.setEntity(new UrlEncodedFormEntity(postData, "ISO-8859-15"));
        }
        // Log.d(TAG, "HTTPClient POST: " + postData);
        request = pr;
    }
    request.addHeader(ACCEPT_ENCODING, GZIP);
    if (referer != null) {
        request.setHeader("Referer", referer);
        // Log.d(TAG, "HTTPClient REF: " + referer);
    }
    if (userAgent != null) {
        request.setHeader("User-Agent", userAgent);
        // Log.d(TAG, "HTTPClient AGENT: " + userAgent);
    }
    // Log.d(TAG, getHeaders(request));
    return httpClient.execute(request);
}

From source file:com.ibm.watson.developer_cloud.service.WatsonService.java

/**
 * Sets the authentication.//from   ww  w . j a va  2 s . co m
 * 
 * @param request
 *            the new authentication
 */
protected void setAuthentication(HttpRequestBase request) {
    if (getApiKey() == null) {
        throw new IllegalArgumentException("apiKey or username and password were not specified");
    } else {
        request.addHeader(AUTHORIZATION, apiKey.startsWith("Basic ") ? apiKey : "Basic " + apiKey);
    }

}

From source file:org.workin.http.httpclient.v4.HttpClientTemplet.java

/**
 * @description HttpRequestBase?Header//w  ww. j  ava  2 s  .  co  m
 * @author <a href="mailto:code727@gmail.com">?</a> 
 * @param httpGet
 */
protected void addHeader(HttpRequestBase httpRequest, HttpForm form) {
    HttpRequestHeader header = form.getHeader();
    if (header != null) {
        Iterator<Entry<String, Object>> headerItem = header.getAttributes().entrySet().iterator();
        while (headerItem.hasNext()) {
            Entry<String, Object> item = headerItem.next();
            httpRequest.addHeader(item.getKey(), item.getKey());
        }
    }
}

From source file:io.apicurio.hub.api.gitlab.GitLabSourceConnector.java

/**
 * Adds security information to the http request.
 * @param request// w ww  .  j  a v  a  2  s .  c  o  m
 */
protected void addSecurity(HttpRequestBase request) throws SourceConnectorException {
    if (this.getExternalTokenType() == TOKEN_TYPE_PAT) {
        request.addHeader("PRIVATE-TOKEN", getExternalToken());
    }
    if (this.getExternalTokenType() == TOKEN_TYPE_OAUTH) {
        request.addHeader("Authorization", "Bearer " + getExternalToken());
    }
}

From source file:com.opower.rest.client.generator.executors.ApacheHttpClient4Executor.java

public void commitHeaders(ClientRequest request, HttpRequestBase httpMethod) {
    MultivaluedMap<String, String> headers = request.getHeaders();
    for (Map.Entry<String, List<String>> header : headers.entrySet()) {
        List<String> values = header.getValue();
        for (String value : values) {
            //               System.out.println(String.format("setting %s = %s", header.getKey(), value));
            httpMethod.addHeader(header.getKey(), value);
        }/* w  w w .  j a v  a 2s . co  m*/
    }
}

From source file:com.comcast.cns.io.HTTPEndpointSyncPublisher.java

private void composeHeader(HttpRequestBase httpRequest) {

    httpRequest.setHeader("x-amz-sns-message-type", this.getMessageType());
    httpRequest.setHeader("x-amz-sns-message-id", this.getMessageId());
    httpRequest.setHeader("x-amz-sns-topic-arn", this.getTopicArn());
    httpRequest.setHeader("x-amz-sns-subscription-arn", this.getSubscriptionArn());
    httpRequest.setHeader("User-Agent", "Cloud Notification Service Agent");

    if (this.getRawMessageDelivery()) {
        httpRequest.addHeader("x-amz-raw-message", "true");
    }/*from w  ww .ja  v a 2  s . c om*/
}

From source file:com.sap.core.odata.fit.ref.AbstractRefTest.java

protected HttpResponse callUri(final ODataHttpMethod httpMethod, final String uri,
        final String additionalHeader, final String additionalHeaderValue, final String requestBody,
        final String requestContentType, final HttpStatusCodes expectedStatusCode) throws Exception {

    HttpRequestBase request = httpMethod == ODataHttpMethod.GET ? new HttpGet()
            : httpMethod == ODataHttpMethod.DELETE ? new HttpDelete()
                    : httpMethod == ODataHttpMethod.POST ? new HttpPost()
                            : httpMethod == ODataHttpMethod.PUT ? new HttpPut() : new HttpPatch();
    request.setURI(URI.create(getEndpoint() + uri));
    if (additionalHeader != null) {
        request.addHeader(additionalHeader, additionalHeaderValue);
    }//w  w w .  j  ava  2s.c o  m
    if (requestBody != null) {
        ((HttpEntityEnclosingRequest) request).setEntity(new StringEntity(requestBody));
        request.setHeader(HttpHeaders.CONTENT_TYPE, requestContentType);
    }

    final HttpResponse response = getHttpClient().execute(request);

    assertNotNull(response);
    assertEquals(expectedStatusCode.getStatusCode(), response.getStatusLine().getStatusCode());

    if (expectedStatusCode == HttpStatusCodes.OK) {
        assertNotNull(response.getEntity());
        assertNotNull(response.getEntity().getContent());
    } else if (expectedStatusCode == HttpStatusCodes.CREATED) {
        assertNotNull(response.getEntity());
        assertNotNull(response.getEntity().getContent());
        assertNotNull(response.getFirstHeader(HttpHeaders.LOCATION));
    } else if (expectedStatusCode == HttpStatusCodes.NO_CONTENT) {
        assertTrue(response.getEntity() == null || response.getEntity().getContent() == null);
    }

    return response;
}