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

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

Introduction

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

Prototype

public boolean containsHeader(String str) 

Source Link

Usage

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

/**
 * Execute the Http request./*from  w ww  .  j  a  v a2 s  . c o  m*/
 * 
 * @param request
 *            the http request
 * 
 * @return the http response
 */
protected HttpResponse execute(HttpRequestBase request) {

    setAuthentication(request);

    if (getEndPoint() == null)
        throw new IllegalArgumentException("service endpoint was not specified");

    if (!request.containsHeader(ACCEPT)) {
        request.addHeader(ACCEPT, getDefaultContentType());
    }

    // from /v1/foo/bar to https://host:port/api/v1/foo/bar
    if (!request.getURI().isAbsolute()) {
        request.setURI(buildRequestURI(request));
    }
    HttpResponse response;

    //HttpHost proxy=new HttpHost("10.100.1.124",3128);

    log.log(Level.FINEST, "Request to: " + request.getURI());
    try {
        response = getHttpClient().execute(request);
        //ConnRouteParams.setDefaultProxy(response.getParams(),proxy);
    } catch (ClientProtocolException e) {
        log.log(Level.SEVERE, "ClientProtocolException", e);
        throw new RuntimeException(e);
    } catch (IOException e) {
        log.log(Level.SEVERE, "IOException", e);
        throw new RuntimeException(e);
    }

    final int status = response.getStatusLine().getStatusCode();
    log.log(Level.FINEST, "Response HTTP Status: " + status);

    if (status >= 200 && status < 300)
        return response;

    // There was a Client Error 4xx or a Server Error 5xx
    // Get the error message and create the exception
    String error = getErrorMessage(response);
    log.log(Level.SEVERE, "HTTP Status: " + status + ", message: " + error);

    switch (status) {
    case HttpStatus.SC_BAD_REQUEST: // HTTP 400
        throw new BadRequestException(error != null ? error : "Bad Request");
    case HttpStatus.SC_UNAUTHORIZED: // HTTP 401
        throw new UnauthorizedException("Unauthorized: Access is denied due to invalid credentials");
    case HttpStatus.SC_FORBIDDEN: // HTTP 403
        throw new ForbiddenException(error != null ? error : "Forbidden: Service refuse the request");
    case HttpStatus.SC_NOT_FOUND: // HTTP 404
        throw new NotFoundException(error != null ? error : "Not found");
    case HttpStatus.SC_NOT_ACCEPTABLE: // HTTP 406
        throw new ForbiddenException(error != null ? error : "Forbidden: Service refuse the request");
    case HttpStatus.SC_REQUEST_TOO_LONG: // HTTP 413
        throw new RequestTooLargeException(error != null ? error
                : "Request too large: The request entity is larger than the server is able to process");
    case HttpStatus.SC_UNSUPPORTED_MEDIA_TYPE: // HTTP 415
        throw new UnsupportedException(error != null ? error
                : "Unsupported MIME type: The request entity has a media type which the server or resource does not support");
    case 429: // HTTP 429
        throw new TooManyRequestsException(error != null ? error : "Too many requests");
    case HttpStatus.SC_INTERNAL_SERVER_ERROR: // HTTP 500
        throw new InternalServerErrorException(error != null ? error : "Internal Server Error");
    case HttpStatus.SC_SERVICE_UNAVAILABLE: // HTTP 503
        throw new ServiceUnavailableException(error != null ? error : "Service Unavailable");
    default: // other errors
        throw new ServiceResponseException(status, error);
    }
}

From source file:com.glodon.paas.document.api.AbstractDocumentAPITest.java

private void setHttpHeaders(HttpRequestBase requestBase, Map<String, String> header) {
    if (header != null && !header.isEmpty()) {
        Set<String> keys = header.keySet();
        Iterator<String> it = keys.iterator();
        while (it.hasNext()) {
            String key = it.next();
            String value = header.get(key);
            if (requestBase != null) {
                requestBase.setHeader(key, value);
            }/*from   w  w w.  j a  va2  s. c  o m*/
        }
    }
    if (!requestBase.containsHeader("Content-type")) {
        requestBase.setHeader("Content-type", "application/json");
    }
    if (!requestBase.containsHeader("Host")) {
        requestBase.setHeader("Host", host + ":" + port);
    }
    if (!requestBase.containsHeader("Accept")) {
        requestBase.setHeader("Accept", "application/json");
    }
}

From source file:org.elasticsearch.xpack.watcher.common.http.HttpClient.java

public HttpResponse execute(HttpRequest request) throws IOException {
    URI uri = createURI(request);

    HttpRequestBase internalRequest;
    if (request.method == HttpMethod.HEAD) {
        internalRequest = new HttpHead(uri);
    } else {/*from   ww  w.j av a  2  s  .c  om*/
        HttpMethodWithEntity methodWithEntity = new HttpMethodWithEntity(uri, request.method.name());
        if (request.hasBody()) {
            ByteArrayEntity entity = new ByteArrayEntity(request.body.getBytes(StandardCharsets.UTF_8));
            String contentType = request.headers().get(HttpHeaders.CONTENT_TYPE);
            if (Strings.hasLength(contentType)) {
                entity.setContentType(contentType);
            } else {
                entity.setContentType(ContentType.TEXT_PLAIN.toString());
            }
            methodWithEntity.setEntity(entity);
        }
        internalRequest = methodWithEntity;
    }
    internalRequest.setHeader(HttpHeaders.ACCEPT_CHARSET, StandardCharsets.UTF_8.name());

    // headers
    if (request.headers().isEmpty() == false) {
        for (Map.Entry<String, String> entry : request.headers.entrySet()) {
            internalRequest.setHeader(entry.getKey(), entry.getValue());
        }
    }

    // BWC - hack for input requests made to elasticsearch that do not provide the right content-type header!
    if (request.hasBody() && internalRequest.containsHeader("Content-Type") == false) {
        XContentType xContentType = XContentFactory.xContentType(request.body());
        if (xContentType != null) {
            internalRequest.setHeader("Content-Type", xContentType.mediaType());
        }
    }

    RequestConfig.Builder config = RequestConfig.custom();
    setProxy(config, request, settingsProxy);
    HttpClientContext localContext = HttpClientContext.create();
    // auth
    if (request.auth() != null) {
        ApplicableHttpAuth applicableAuth = httpAuthRegistry.createApplicable(request.auth);
        CredentialsProvider credentialsProvider = new BasicCredentialsProvider();
        applicableAuth.apply(credentialsProvider, new AuthScope(request.host, request.port));
        localContext.setCredentialsProvider(credentialsProvider);

        // preemptive auth, no need to wait for a 401 first
        AuthCache authCache = new BasicAuthCache();
        BasicScheme basicAuth = new BasicScheme();
        authCache.put(new HttpHost(request.host, request.port, request.scheme.scheme()), basicAuth);
        localContext.setAuthCache(authCache);
    }

    // timeouts
    if (request.connectionTimeout() != null) {
        config.setConnectTimeout(Math.toIntExact(request.connectionTimeout.millis()));
    } else {
        config.setConnectTimeout(Math.toIntExact(defaultConnectionTimeout.millis()));
    }

    if (request.readTimeout() != null) {
        config.setSocketTimeout(Math.toIntExact(request.readTimeout.millis()));
        config.setConnectionRequestTimeout(Math.toIntExact(request.readTimeout.millis()));
    } else {
        config.setSocketTimeout(Math.toIntExact(defaultReadTimeout.millis()));
        config.setConnectionRequestTimeout(Math.toIntExact(defaultReadTimeout.millis()));
    }

    internalRequest.setConfig(config.build());

    try (CloseableHttpResponse response = SocketAccess
            .doPrivileged(() -> client.execute(internalRequest, localContext))) {
        // headers
        Header[] headers = response.getAllHeaders();
        Map<String, String[]> responseHeaders = new HashMap<>(headers.length);
        for (Header header : headers) {
            if (responseHeaders.containsKey(header.getName())) {
                String[] old = responseHeaders.get(header.getName());
                String[] values = new String[old.length + 1];

                System.arraycopy(old, 0, values, 0, old.length);
                values[values.length - 1] = header.getValue();

                responseHeaders.put(header.getName(), values);
            } else {
                responseHeaders.put(header.getName(), new String[] { header.getValue() });
            }
        }

        final byte[] body;
        // not every response has a content, i.e. 204
        if (response.getEntity() == null) {
            body = new byte[0];
        } else {
            try (ByteArrayOutputStream outputStream = new ByteArrayOutputStream()) {
                try (InputStream is = new SizeLimitInputStream(maxResponseSize,
                        response.getEntity().getContent())) {
                    Streams.copy(is, outputStream);
                }
                body = outputStream.toByteArray();
            }
        }
        return new HttpResponse(response.getStatusLine().getStatusCode(), body, responseHeaders);
    }
}

From source file:org.apache.juneau.rest.client.RestClient.java

/**
 * Perform a generic REST call./*from   ww w  . j a  v  a 2 s  .c o m*/
 *
 * @param method The method name (e.g. <js>"GET"</js>, <js>"OPTIONS"</js>).
 * @param url The URL of the remote REST resource.  Can be any of the following:  {@link String}, {@link URI}, {@link URL}.
 * @param hasContent Boolean flag indicating if the specified request has content associated with it.
 * @return A {@link RestCall} object that can be further tailored before executing the request
 *    and getting the response as a parsed object.
 * @throws RestCallException If any authentication errors occurred.
 */
public RestCall doCall(String method, Object url, boolean hasContent) throws RestCallException {
    if (isClosed) {
        Exception e2 = null;
        if (closedStack != null) {
            e2 = new Exception("Creation stack:");
            e2.setStackTrace(closedStack);
            throw new RestCallException(
                    "RestClient.close() has already been called.  This client cannot be reused.").initCause(e2);
        }
        throw new RestCallException(
                "RestClient.close() has already been called.  This client cannot be reused.  Closed location stack trace can be displayed by setting the system property 'org.apache.juneau.rest.client.RestClient.trackCreation' to true.");
    }

    HttpRequestBase req = null;
    RestCall restCall = null;
    final String methodUC = method.toUpperCase(Locale.ENGLISH);
    try {
        if (hasContent) {
            req = new HttpEntityEnclosingRequestBase() {
                @Override /* HttpRequest */
                public String getMethod() {
                    return methodUC;
                }
            };
            restCall = new RestCall(this, req, toURI(url));
        } else {
            req = new HttpRequestBase() {
                @Override /* HttpRequest */
                public String getMethod() {
                    return methodUC;
                }
            };
            restCall = new RestCall(this, req, toURI(url));
        }
    } catch (URISyntaxException e1) {
        throw new RestCallException(e1);
    }
    for (Map.Entry<String, ? extends Object> e : headers.entrySet())
        restCall.header(e.getKey(), e.getValue());

    if (parser != null && !req.containsHeader("Accept"))
        req.setHeader("Accept", parser.getPrimaryMediaType().toString());

    return restCall;
}

From source file:de.betterform.connector.http.AbstractHTTPConnector.java

protected void execute(HttpRequestBase httpRequestBase) throws Exception {
    //      (new HttpClient()).executeMethod(httpMethod);
    //HttpClient client = new HttpClient();
    HttpParams httpParams = new BasicHttpParams();

    DefaultHttpClient client = ConnectorFactory.getFactory().getHttpClient(httpParams);

    if (!getContext().containsKey(AbstractHTTPConnector.SSL_CUSTOM_SCHEME)) {
        LOGGER.debug("SSL_CUSTOM_SCHEME");
        LOGGER.debug("SSL_CUSTOM_SCHEME: Factory: "
                + Config.getInstance().getProperty(AbstractHTTPConnector.HTTPCLIENT_SSL_CONTEXT));
        String contextPath = Config.getInstance().getProperty(AbstractHTTPConnector.HTTPCLIENT_SSL_CONTEXT);
        if (contextPath != null) {
            initSSLScheme(contextPath);/*w  ww .j a  v a2 s. c  om*/
        }
    }

    if (LOGGER.isDebugEnabled()) {
        LOGGER.debug("context params>>>");
        Map map = getContext();
        Iterator keys = map.keySet().iterator();
        while (keys.hasNext()) {
            String key = keys.next().toString();
            Object value = map.get(key);
            if (value != null)
                LOGGER.debug(key + "=" + value.toString());
        }
        LOGGER.debug("<<<end params");
    }
    String username = null;
    String password = null;
    String realm = null;

    //add custom header to signal XFormsFilter to not process this internal request
    //httpMethod.setRequestHeader(BetterFORMConstants.BETTERFORM_INTERNAL,"true");
    httpRequestBase.addHeader(BetterFORMConstants.BETTERFORM_INTERNAL, "true");

    /// *** copy all keys in map HTTP_REQUEST_HEADERS as http-submissionHeaders
    if (getContext().containsKey(HTTP_REQUEST_HEADERS)) {
        RequestHeaders httpRequestHeaders = (RequestHeaders) getContext().get(HTTP_REQUEST_HEADERS);

        // Iterator it =
        Map headersToAdd = new HashMap();
        for (RequestHeader header : httpRequestHeaders.getAllHeaders()) {
            String headername = header.getName();
            String headervalue = header.getValue();

            if (headername.equals("username")) {
                username = headervalue;
            } else if (headername.equals("password")) {
                password = headervalue;
            } else if (headername.equals("realm")) {
                realm = headervalue;
            } else {
                if (headersToAdd.containsKey(headername)) {
                    String formerValue = (String) headersToAdd.get(headername);
                    headersToAdd.put(headername, formerValue + "," + headervalue);
                } else {
                    if (headername.equals("accept-encoding")) {
                        // do nothing
                        LOGGER.debug("do not add accept-encoding:" + headervalue + " for request");
                    } else {
                        headersToAdd.put(headername, headervalue);
                        if (LOGGER.isDebugEnabled()) {
                            LOGGER.debug("setting header: " + headername + " value: " + headervalue);
                        }
                    }
                }
            }
        }
        Iterator keyIterator = headersToAdd.keySet().iterator();
        while (keyIterator.hasNext()) {
            String key = (String) keyIterator.next();
            //httpMethod.setRequestHeader(new Header(key,(String) headersToAdd.get(key)));
            httpRequestBase.setHeader(key, (String) headersToAdd.get(key));
            //httpRequestBase.addHeader(key, (String) headersToAdd.get(key));
        }
    }
    if (httpRequestBase.containsHeader("Content-Length")) {
        //remove content-length if present httpclient will recalucalte the value.
        httpRequestBase.removeHeaders("Content-Length");
    }
    if (username != null && password != null) {
        URI targetURI = null;
        //targetURI = httpMethod.getURI();
        targetURI = httpRequestBase.getURI();
        //client.getParams().setAuthenticationPreemptive(true);

        Credentials defaultcreds = new UsernamePasswordCredentials(username, password);
        if (realm == null) {
            realm = AuthScope.ANY_REALM;
        }
        //client.getState().setCredentials(new AuthScope(targetURI.getHost(), targetURI.getPort(), realm), defaultcreds);
        client.getCredentialsProvider()
                .setCredentials(new AuthScope(targetURI.getHost(), targetURI.getPort(), realm), defaultcreds);
        AuthCache authCache = new BasicAuthCache();
        BasicScheme basicAuth = new BasicScheme();

        authCache.put(new HttpHost(targetURI.getHost()), basicAuth);
        BasicHttpContext localContext = new BasicHttpContext();
        localContext.setAttribute(ClientContext.AUTH_CACHE, authCache);

        //Needed? httpMethod.setDoAuthentication(true);

    }
    //alternative method for non-tomcat servers
    if (getContext().containsKey(REQUEST_COOKIE)) {
        //HttpState state = client.getState();
        HttpParams state = client.getParams();

        //state.setCookiePolicy(CookiePolicy.COMPATIBILITY);
        state.setParameter(ClientPNames.COOKIE_POLICY, CookiePolicy.BROWSER_COMPATIBILITY);

        if (getContext().get(REQUEST_COOKIE) instanceof Cookie[]) {
            Cookie[] cookiesIn = (Cookie[]) getContext().get(REQUEST_COOKIE);
            if (cookiesIn[0] != null) {
                for (int i = 0; i < cookiesIn.length; i++) {
                    Cookie cookie = cookiesIn[i];
                    //state.addCookie(cookie);
                    client.getCookieStore().addCookie(cookie);
                }
                /*
                  Cookie[] cookies = state.getCookies();
                        
                Header cookieOut = new CookieSpecBase().formatCookieHeader(cookies);
                httpMethod.setRequestHeader(cookieOut);
                client.setState(state);
                  */
                List<Cookie> cookies = client.getCookieStore().getCookies();
                List<Header> cookieHeaders = new BrowserCompatSpec().formatCookies(cookies);
                Header[] headers = cookieHeaders.toArray(new Header[0]);

                for (int i = 0; i < headers.length; i++) {
                    httpRequestBase.addHeader(headers[i]);
                }

                client.setParams(state);
            }
        } else {
            throw new MalformedCookieException(
                    "Cookies must be passed as org.apache.commons.httpclient.Cookie objects.");
        }
    }

    if (getContext().containsKey(AbstractHTTPConnector.SSL_CUSTOM_SCHEME)) {
        LOGGER.debug("Using customSSL-Protocol-Handler");
        Iterator<Scheme> schemes = ((Vector<Scheme>) getContext().get(AbstractHTTPConnector.SSL_CUSTOM_SCHEME))
                .iterator();

        while (schemes.hasNext()) {
            client.getConnectionManager().getSchemeRegistry().register(schemes.next());
        }
    }

    if (httpRequestBase.getURI().isAbsolute()) {
        httpRequestBase.setHeader("host", httpRequestBase.getURI().getHost());
    }

    HttpResponse httpResponse = client.execute(httpRequestBase);
    statusCode = httpResponse.getStatusLine().getStatusCode();
    reasonPhrase = httpResponse.getStatusLine().getReasonPhrase();
    try {
        if (statusCode >= 300) {
            // Allow 302 only
            if (statusCode != 302) {
                throw new XFormsInternalSubmitException(statusCode, reasonPhrase,
                        EntityUtils.toString(httpResponse.getEntity()), XFormsConstants.RESOURCE_ERROR);
            }
        }
        this.handleHttpMethod(httpResponse);
    } catch (Exception e) {

        LOGGER.trace("AbstractHTTPConnector Exception: ", e);
        try {
            throw new XFormsInternalSubmitException(httpResponse.getStatusLine().getStatusCode(),
                    httpResponse.getStatusLine().getReasonPhrase(),
                    EntityUtils.toString(httpResponse.getEntity()), XFormsConstants.RESOURCE_ERROR);
        } catch (IOException e1) {
            throw new XFormsInternalSubmitException(httpResponse.getStatusLine().getStatusCode(),
                    httpResponse.getStatusLine().getReasonPhrase(), XFormsConstants.RESOURCE_ERROR);
        }
    }

}