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:gr.ndre.scuttloid.APITask.java

protected void addAuthHeader(HttpRequestBase request) {
    String authentication = this.username + ":" + this.password;
    String encodedAuthentication = Base64.encodeToString(authentication.getBytes(), Base64.NO_WRAP);
    request.addHeader("Authorization", "Basic " + encodedAuthentication);
}

From source file:org.apache.metamodel.neo4j.Neo4jRequestWrapper.java

public String executeRestRequest(HttpRequestBase httpRequest, String username, String password) {
    if ((username != null) && (password != null)) {
        String base64credentials = BaseEncoding.base64()
                .encode((username + ":" + password).getBytes(StandardCharsets.UTF_8));
        httpRequest.addHeader("Authorization", "Basic " + base64credentials);
    }// ww w.j  a  va2s . c  om

    try {
        CloseableHttpResponse response = _httpClient.execute(_httpHost, httpRequest);
        if (response.getEntity() != null) {
            return EntityUtils.toString(response.getEntity());
        }
        return null;
    } catch (ClientProtocolException e) {
        logger.error("An error occured while executing " + httpRequest, e);
        throw new IllegalStateException(e);
    } catch (IOException e) {
        logger.error("An error occured while executing " + httpRequest, e);
        throw new IllegalStateException(e);
    }
}

From source file:org.apache.manifoldcf.crawler.connectors.jira.JiraSession.java

private void getRest(String rightside, JiraJSONResponse 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);/*from  w w w. j av a  2  s  .co m*/

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

    final HttpRequestBase method = new HttpGet(host.toURI() + path + rightside);
    method.addHeader("Accept", "application/json");

    try {
        HttpResponse httpResponse = httpClient.execute(method, localContext);
        int resultCode = httpResponse.getStatusLine().getStatusCode();
        if (resultCode != 200)
            throw new IOException(
                    "Unexpected result code " + resultCode + ": " + convertToString(httpResponse));
        Object jo = convertToJSON(httpResponse);
        response.acceptJSONObject(jo);
    } finally {
        method.abort();
    }
}

From source file:com.arrow.acs.client.api.ApiAbstract.java

private void addHeaders(HttpRequestBase msg, Instant timestamp, String signature) {
    Validate.notNull(msg, "msg is null");
    Validate.notNull(timestamp, "timestamp is null");
    Validate.notEmpty(apiConfig.getApiKey(), "apiKey is empty");
    msg.addHeader(HttpHeaders.CONTENT_TYPE, MIME_APPLICATION_JSON);
    msg.addHeader(HttpHeaders.ACCEPT, MIME_APPLICATION_JSON);
    msg.addHeader(ApiHeaders.X_ARROW_APIKEY, apiConfig.getApiKey());
    msg.addHeader(ApiHeaders.X_ARROW_DATE, timestamp.toString());
    msg.addHeader(ApiHeaders.X_ARROW_VERSION, ApiHeaders.X_ARROW_VERSION_1);
    msg.addHeader(ApiHeaders.X_ARROW_SIGNATURE, signature);
}

From source file:mobi.jenkinsci.alm.assembla.client.AssemblaClient.java

private void setRequestHeaders(final HttpRequestBase req, final boolean autoLogin) {
    if (accessToken != null) {
        req.addHeader("Authorization", "Bearer " + accessToken.access_token);
    }/*from w w w  .j a  v a2 s  .com*/
    if (req.getURI().getPath().endsWith(".json")) {
        req.addHeader(HttpHeaders.ACCEPT, "application/json");
    }
}

From source file:org.cloudsmith.stackhammer.api.client.StackHammerClient.java

protected void configureRequest(final HttpRequestBase request) {
    if (credentials != null)
        request.addHeader(HttpHeaders.AUTHORIZATION, credentials);
    request.addHeader(HttpHeaders.USER_AGENT, userAgent);
    request.addHeader(HttpHeaders.ACCEPT, "application/vnd.stackhammer.beta+json"); //$NON-NLS-1$
}

From source file:de.ub0r.android.websms.connector.common.Utils.java

/**
 * Get a fresh HTTP-Connection.//  w w  w  .  j  av a2s . co  m
 * 
 * @param o
 *            {@link HttpOptions}
 * @return the connection
 * @throws IOException
 *             IOException
 */
public static HttpResponse getHttpClient(final HttpOptions o) throws IOException {
    if (verboseLog) {
        Log.d(TAG, "HTTPClient URL: " + o.url);
    } else {
        Log.d(TAG, "HTTPClient URL: " + o.url.replaceFirst("\\?.*", ""));
    }

    if (httpClient == null) {
        SchemeRegistry registry = new SchemeRegistry();
        registry.register(new Scheme("http", new PlainSocketFactory(), PORT_HTTP));
        SocketFactory httpsSocketFactory;
        if (o.trustAll) {
            httpsSocketFactory = new FakeSocketFactory();
        } else if (o.knownFingerprints != null && o.knownFingerprints.length > 0) {
            httpsSocketFactory = new FakeSocketFactory(o.knownFingerprints);
        } else {
            httpsSocketFactory = SSLSocketFactory.getSocketFactory();
        }
        registry.register(new Scheme("https", httpsSocketFactory, PORT_HTTPS));
        HttpParams params = new BasicHttpParams();

        HttpConnectionParams.setConnectionTimeout(params, o.timeout);
        HttpConnectionParams.setSoTimeout(params, o.timeout);

        if (o.maxConnections > 0) {
            ConnManagerParams.setMaxConnectionsPerRoute(params, new ConnPerRoute() {
                public int getMaxForRoute(final HttpRoute httproute) {
                    return o.maxConnections;
                }
            });
        }

        httpClient = new DefaultHttpClient(new ThreadSafeClientConnManager(params, registry), params);

        httpClient.addResponseInterceptor(new HttpResponseInterceptor() {
            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 (HeaderElement codec : codecs) {
                        if (codec.getName().equalsIgnoreCase(GZIP)) {
                            response.setEntity(new GzipDecompressingEntity(response.getEntity()));
                            return;
                        }
                    }
                }
            }
        });
    }
    if (o.cookies != null && o.cookies.size() > 0) {
        final int l = o.cookies.size();
        CookieStore cs = httpClient.getCookieStore();
        for (int i = 0; i < l; i++) {
            cs.addCookie(o.cookies.get(i));
        }
    }
    // . Log.d(TAG, getCookies(httpClient));

    HttpRequestBase request;
    if (o.postData == null) {
        request = new HttpGet(o.url);
    } else {
        HttpPost pr = new HttpPost(o.url);
        pr.setEntity(o.postData);
        // . Log.d(TAG, "HTTPClient POST: " + postData);
        request = pr;
    }
    request.addHeader("Accept", "*/*");
    request.addHeader(ACCEPT_ENCODING, GZIP);

    if (o.referer != null) {
        request.setHeader("Referer", o.referer);
        if (verboseLog) {
            Log.d(TAG, "HTTPClient REF: " + o.referer);
        }
    }

    if (o.userAgent != null) {
        request.setHeader("User-Agent", o.userAgent);
        if (verboseLog) {
            Log.d(TAG, "HTTPClient AGENT: " + o.userAgent);
        }
    }

    addHeaders(request, o.headers);

    if (verboseLog) {
        Log.d(TAG, "HTTP " + request.getMethod() + " " + request.getURI());
        Log.d(TAG, getHeaders(request));
        if (request instanceof HttpPost) {
            Log.d(TAG, "");
            Log.d(TAG, ((HttpPost) request).getEntity().getContent());
        }
    }
    return httpClient.execute(request);
}

From source file:com.strato.hidrive.api.connection.httpgateway.HTTPGateway.java

public HTTPGatewayResult<T> sendRequest(String baseUri, Request request, ResponseHandler<T> responseHandler) {
    try {/*from ww w. j a v  a2  s.c  o  m*/
        HttpRequestBase httpRequest = request.createHttpRequest(baseUri);

        if (uriRedirector != null) {
            httpRequest.setURI(new URI(uriRedirector.redirectUri(httpRequest.getURI().toString())));
        }

        if (accessToken.length() != 0) {
            httpRequest.addHeader("Authorization", "Bearer " + Base64Utils.base64Encode(accessToken));
        }

        httpClient.setCookieStore(cookieStore);

        T responseData = this.httpClient.execute(httpRequest, responseHandler,
                HttpClientManager.getInstance().getLocalHttpContext());
        List<Cookie> cookies = this.httpClient.getCookieStore().getCookies();
        if (cookies.isEmpty()) {
            Log.i("Cookie", "None");
        } else {
            for (int i = 0; i < cookies.size(); i++) {
                Log.i("Cookie", "- " + cookies.get(i).toString());
            }
        }

        return new HTTPGatewayResult<T>(null, false, new Response<T>(responseData));
    } catch (Exception e) {
        e.printStackTrace();
        return new HTTPGatewayResult<T>(e, false, null);
    }
}

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

/**
 * This method sets the headers to the http request base. This implementation adds the custom headers configured on this pool and subsequently adds
 * the headers that came with the specified Http request if {@link HttpConnectionPool#isForwardHeaders()} is set to 'true' and in this case sets the
 * {@link HTTP#TARGET_HOST} to the the value <HttpConnectionPool{@link #getHost()}:HttpConnectionPool{@link #getPort()}. Sub-types may override this method
 * to change this behavior.//from  w  ww  . j av a 2 s.  c  o m
 *
 * @param request {@link HttpRequestBase} to add headers to.
 * @param requestHeaders the List of header tuples which are added to the request
 */
protected void setRequestHeaders(HttpRequestBase request, List<Map.Entry<String, String>> requestHeaders) {
    if (this.headers != null && this.headers.isEmpty()) {
        for (String headerKey : this.headers.keySet()) {
            request.addHeader(headerKey, this.headers.get(headerKey));
        }
    }
    if (this.isForwardHeaders()) { // forward request headers only if specified

        if (requestHeaders != null && !requestHeaders.isEmpty()) {
            for (Map.Entry<String, String> headerMap : requestHeaders) {
                if (!HttpConnectionPool.REMOVE_HEADERS.contains(headerMap.getKey())) {
                    request.addHeader(headerMap.getKey(), headerMap.getValue());
                }
            }
        }
        // replace "Host" header with the that of the real target host
        request.setHeader(HTTP.TARGET_HOST, this.getHost() + ":" + this.getPort());
    }
}

From source file:com.cloudant.mazha.HttpRequests.java

/**
 * Executes a HTTP request.//  w  w  w. java2s .c o m
 *
 * @param request The HTTP request to execute.
 * @return {@link org.apache.http.HttpResponse}
 */
private HttpResponse executeRequest(HttpRequestBase request) {
    try {
        if (authHeaderValue != null) {
            request.addHeader("Authorization", authHeaderValue);
        }
        HttpResponse response = httpClient.execute(host, request, context);
        validate(request, response);
        return response;
    } catch (IOException e) {
        request.abort();
        throw new ServerException(e);
    }
}