Example usage for io.vertx.core.http HttpClientRequest end

List of usage examples for io.vertx.core.http HttpClientRequest end

Introduction

In this page you can find the example usage for io.vertx.core.http HttpClientRequest end.

Prototype

@Override
void end(Handler<AsyncResult<Void>> handler);

Source Link

Document

Same as #end() but with an handler called when the operation completes

Usage

From source file:com.deblox.solacemonitor.MonitorVerticle.java

License:Apache License

/**
 * Perform the actual rest call/*w w  w. jav a  2  s. c  om*/
 *
 * @param metricName the named metric as in conf.json
 * @param handler the handler to call with the results
 */
public void getRest(String metricName, Handler handler) {

    try {

        if (host == null) {
            logger.warn("no config");

        } else {

            logger.debug(uuid + " getting metric: " + metricName + " from: " + host);

            HttpClientRequest req;

            // GET
            if (method.equals("GET")) {
                req = client.post(port, host, uri, resp -> {
                    resp.bodyHandler(body -> {
                        logger.debug("Response: " + body.toString());
                        handler.handle(body.toString());
                    });

                });

                // POST
            } else if (method.equals("POST")) {
                req = client.post(port, host, uri, resp -> {
                    resp.bodyHandler(body -> {
                        logger.debug("Response: " + body.toString());
                        handler.handle(body.toString());
                    });

                });

                // PUT
            } else if (method.equals("PUT")) {
                req = client.put(port, host, uri, resp -> {
                    resp.bodyHandler(body -> {
                        logger.debug("Response: " + body.toString());
                        handler.handle(body.toString());
                    });

                });

                // FTS
            } else {
                throw new Exception("method " + method + " is not supported");
            }

            if (config.getBoolean("basic_auth", true)) {
                req.putHeader(HttpHeaders.Names.AUTHORIZATION,
                        "Basic " + Base64.getEncoder().encodeToString(credentials.getBytes()));
            }

            req.end(config.getJsonObject("metrics").getJsonObject(metricName).getString("request"));

        }
    } catch (Exception e) {
        logger.warn(e.getMessage());

    }
}

From source file:examples.HTTPExamples.java

License:Open Source License

public void example36(HttpClientRequest request) {

    // Write string and end the request (send it) in a single call
    request.end("some simple data");

    // Write buffer and end the request (send it) in a single call
    Buffer buffer = Buffer.buffer().appendDouble(12.34d).appendLong(432l);
    request.end(buffer);//from  w  ww  .  ja va2s.c  o m

}

From source file:examples.HTTPExamples.java

License:Open Source License

public void example40(HttpClientRequest request) {
    // End the request with a string
    request.end("some-data");

    // End it with a buffer
    Buffer buffer = Buffer.buffer().appendFloat(12.3f).appendInt(321);
    request.end(buffer);/*  w  ww.  ja  v a2 s .  c  o  m*/
}

From source file:io.advantageous.qbit.vertx.http.client.HttpVertxClient.java

License:Apache License

@Override
public void sendHttpRequest(final HttpRequest request) {

    checkClosed();/*from   www. j  a v  a2 s . co  m*/

    if (trace) {
        logger.debug(sputs("HTTP CLIENT: sendHttpRequest:: \n{}\n", request, "\nparams\n", request.params()));
    }

    final String uri = getURICreateParamsIfNeeded(request);

    final HttpMethod httpMethod = HttpMethod.valueOf(request.getMethod());

    final HttpClientRequest httpClientRequest = httpClient.request(httpMethod, uri,
            httpClientResponse -> handleResponse(request, httpClientResponse));

    final MultiMap<String, String> headers = request.getHeaders();

    httpClientRequest.exceptionHandler(error -> {

        if (error instanceof ConnectException) {
            closed.set(true);
            try {
                stop();
            } catch (Exception ex) {

                errorHandler.accept(ex);
                logger.warn("Unable to stop client " + "after failed connection", ex);
            }
            request.getReceiver().errorWithCode("\"Client connection was closed\"",
                    HttpStatus.SERVICE_UNAVAILABLE);
            logger.warn("Connection error", error);
        } else {
            logger.error("Unable to connect to " + host + " port " + port, error);
        }

        errorHandler.accept(error);
    });

    if (headers != null) {

        for (String key : headers.keySet()) {
            httpClientRequest.putHeader(key, headers.getAll(key));
        }
    }

    final byte[] body = request.getBody();

    if (keepAlive) {
        httpClientRequest.putHeader(HttpHeaders.CONNECTION, HttpHeaders.KEEP_ALIVE);
    }

    if (body != null && body.length > 0) {

        httpClientRequest.putHeader(HttpHeaders.CONTENT_LENGTH, Integer.toString(body.length));
        if (request.getContentType() != null) {

            httpClientRequest.putHeader("Content-Type", request.getContentType());
        }
        httpClientRequest.end(Buffer.buffer(request.getBody()));

    } else {
        httpClientRequest.end();
    }

    if (trace)
        logger.trace("HttpClientVertx::SENT \n{}", request);

}

From source file:io.gravitee.gateway.services.healthcheck.http.HttpEndpointRuleHandler.java

License:Apache License

@Override
public void handle(Long timer) {
    HttpEndpoint endpoint = (HttpEndpoint) rule.endpoint();

    logger.debug("Running health-check for endpoint: {} [{}]", endpoint.getName(), endpoint.getTarget());

    // Run request for each step
    for (io.gravitee.definition.model.services.healthcheck.Step step : rule.steps()) {
        try {/*  www .ja  va 2 s  . c o m*/
            URI hcRequestUri = create(endpoint.getTarget(), step.getRequest());

            // Prepare HTTP client
            HttpClientOptions httpClientOptions = new HttpClientOptions().setMaxPoolSize(1).setKeepAlive(false)
                    .setTcpKeepAlive(false);

            if (endpoint.getHttpClientOptions() != null) {
                httpClientOptions
                        .setIdleTimeout((int) (endpoint.getHttpClientOptions().getIdleTimeout() / 1000))
                        .setConnectTimeout((int) endpoint.getHttpClientOptions().getConnectTimeout())
                        .setTryUseCompression(endpoint.getHttpClientOptions().isUseCompression());
            }

            // Configure HTTP proxy
            HttpProxy proxy = endpoint.getHttpProxy();
            if (proxy != null && proxy.isEnabled()) {
                ProxyOptions proxyOptions = new ProxyOptions().setHost(proxy.getHost()).setPort(proxy.getPort())
                        .setUsername(proxy.getUsername()).setPassword(proxy.getPassword())
                        .setType(ProxyType.valueOf(proxy.getType().name()));

                httpClientOptions.setProxyOptions(proxyOptions);
            }

            HttpClientSslOptions sslOptions = endpoint.getHttpClientSslOptions();

            if (HTTPS_SCHEME.equalsIgnoreCase(hcRequestUri.getScheme())) {
                // Configure SSL
                httpClientOptions.setSsl(true);

                if (sslOptions != null) {
                    httpClientOptions.setVerifyHost(sslOptions.isHostnameVerifier())
                            .setTrustAll(sslOptions.isTrustAll());

                    // Client trust configuration
                    if (!sslOptions.isTrustAll() && sslOptions.getTrustStore() != null) {
                        switch (sslOptions.getTrustStore().getType()) {
                        case PEM:
                            PEMTrustStore pemTrustStore = (PEMTrustStore) sslOptions.getTrustStore();
                            PemTrustOptions pemTrustOptions = new PemTrustOptions();
                            if (pemTrustStore.getPath() != null && !pemTrustStore.getPath().isEmpty()) {
                                pemTrustOptions.addCertPath(pemTrustStore.getPath());
                            } else if (pemTrustStore.getContent() != null
                                    && !pemTrustStore.getContent().isEmpty()) {
                                pemTrustOptions.addCertValue(
                                        io.vertx.core.buffer.Buffer.buffer(pemTrustStore.getContent()));
                            } else {
                                throw new EndpointException(
                                        "Missing PEM certificate value for endpoint " + endpoint.getName());
                            }
                            httpClientOptions.setPemTrustOptions(pemTrustOptions);
                            break;
                        case PKCS12:
                            PKCS12TrustStore pkcs12TrustStore = (PKCS12TrustStore) sslOptions.getTrustStore();
                            PfxOptions pfxOptions = new PfxOptions();
                            pfxOptions.setPassword(pkcs12TrustStore.getPassword());
                            if (pkcs12TrustStore.getPath() != null && !pkcs12TrustStore.getPath().isEmpty()) {
                                pfxOptions.setPath(pkcs12TrustStore.getPath());
                            } else if (pkcs12TrustStore.getContent() != null
                                    && !pkcs12TrustStore.getContent().isEmpty()) {
                                pfxOptions.setValue(
                                        io.vertx.core.buffer.Buffer.buffer(pkcs12TrustStore.getContent()));
                            } else {
                                throw new EndpointException(
                                        "Missing PKCS12 value for endpoint " + endpoint.getName());
                            }
                            httpClientOptions.setPfxTrustOptions(pfxOptions);
                            break;
                        case JKS:
                            JKSTrustStore jksTrustStore = (JKSTrustStore) sslOptions.getTrustStore();
                            JksOptions jksOptions = new JksOptions();
                            jksOptions.setPassword(jksTrustStore.getPassword());
                            if (jksTrustStore.getPath() != null && !jksTrustStore.getPath().isEmpty()) {
                                jksOptions.setPath(jksTrustStore.getPath());
                            } else if (jksTrustStore.getContent() != null
                                    && !jksTrustStore.getContent().isEmpty()) {
                                jksOptions.setValue(
                                        io.vertx.core.buffer.Buffer.buffer(jksTrustStore.getContent()));
                            } else {
                                throw new EndpointException(
                                        "Missing JKS value for endpoint " + endpoint.getName());
                            }
                            httpClientOptions.setTrustStoreOptions(jksOptions);
                            break;
                        }
                    }

                    // Client authentication configuration
                    if (sslOptions.getKeyStore() != null) {
                        switch (sslOptions.getKeyStore().getType()) {
                        case PEM:
                            PEMKeyStore pemKeyStore = (PEMKeyStore) sslOptions.getKeyStore();
                            PemKeyCertOptions pemKeyCertOptions = new PemKeyCertOptions();
                            if (pemKeyStore.getCertPath() != null && !pemKeyStore.getCertPath().isEmpty()) {
                                pemKeyCertOptions.setCertPath(pemKeyStore.getCertPath());
                            } else if (pemKeyStore.getCertContent() != null
                                    && !pemKeyStore.getCertContent().isEmpty()) {
                                pemKeyCertOptions.setCertValue(
                                        io.vertx.core.buffer.Buffer.buffer(pemKeyStore.getCertContent()));
                            }
                            if (pemKeyStore.getKeyPath() != null && !pemKeyStore.getKeyPath().isEmpty()) {
                                pemKeyCertOptions.setKeyPath(pemKeyStore.getKeyPath());
                            } else if (pemKeyStore.getKeyContent() != null
                                    && !pemKeyStore.getKeyContent().isEmpty()) {
                                pemKeyCertOptions.setKeyValue(
                                        io.vertx.core.buffer.Buffer.buffer(pemKeyStore.getKeyContent()));
                            }
                            httpClientOptions.setPemKeyCertOptions(pemKeyCertOptions);
                            break;
                        case PKCS12:
                            PKCS12KeyStore pkcs12KeyStore = (PKCS12KeyStore) sslOptions.getKeyStore();
                            PfxOptions pfxOptions = new PfxOptions();
                            pfxOptions.setPassword(pkcs12KeyStore.getPassword());
                            if (pkcs12KeyStore.getPath() != null && !pkcs12KeyStore.getPath().isEmpty()) {
                                pfxOptions.setPath(pkcs12KeyStore.getPath());
                            } else if (pkcs12KeyStore.getContent() != null
                                    && !pkcs12KeyStore.getContent().isEmpty()) {
                                pfxOptions.setValue(
                                        io.vertx.core.buffer.Buffer.buffer(pkcs12KeyStore.getContent()));
                            }
                            httpClientOptions.setPfxKeyCertOptions(pfxOptions);
                            break;
                        case JKS:
                            JKSKeyStore jksKeyStore = (JKSKeyStore) sslOptions.getKeyStore();
                            JksOptions jksOptions = new JksOptions();
                            jksOptions.setPassword(jksKeyStore.getPassword());
                            if (jksKeyStore.getPath() != null && !jksKeyStore.getPath().isEmpty()) {
                                jksOptions.setPath(jksKeyStore.getPath());
                            } else if (jksKeyStore.getContent() != null
                                    && !jksKeyStore.getContent().isEmpty()) {
                                jksOptions
                                        .setValue(io.vertx.core.buffer.Buffer.buffer(jksKeyStore.getContent()));
                            }
                            httpClientOptions.setKeyStoreOptions(jksOptions);
                            break;
                        }
                    }
                }
            }

            HttpClient httpClient = vertx.createHttpClient(httpClientOptions);

            final int port = hcRequestUri.getPort() != -1 ? hcRequestUri.getPort()
                    : (HTTPS_SCHEME.equals(hcRequestUri.getScheme()) ? 443 : 80);

            String relativeUri = (hcRequestUri.getRawQuery() == null) ? hcRequestUri.getRawPath()
                    : hcRequestUri.getRawPath() + '?' + hcRequestUri.getRawQuery();

            // Run health-check
            HttpClientRequest healthRequest = httpClient.request(
                    HttpMethod.valueOf(step.getRequest().getMethod().name().toUpperCase()), port,
                    hcRequestUri.getHost(), relativeUri);

            // Set timeout on request
            if (endpoint.getHttpClientOptions() != null) {
                healthRequest.setTimeout(endpoint.getHttpClientOptions().getReadTimeout());
            }

            // Prepare request
            if (step.getRequest().getHeaders() != null) {
                step.getRequest().getHeaders().forEach(
                        httpHeader -> healthRequest.headers().set(httpHeader.getName(), httpHeader.getValue()));
            }

            final EndpointStatus.Builder healthBuilder = EndpointStatus
                    .forEndpoint(rule.api(), endpoint.getName()).on(currentTimeMillis());

            long startTime = currentTimeMillis();

            Request request = new Request();
            request.setMethod(step.getRequest().getMethod());
            request.setUri(hcRequestUri.toString());

            healthRequest.handler(response -> response.bodyHandler(buffer -> {
                long endTime = currentTimeMillis();
                logger.debug("Health-check endpoint returns a response with a {} status code",
                        response.statusCode());

                String body = buffer.toString();

                EndpointStatus.StepBuilder stepBuilder = validateAssertions(step,
                        new EvaluableHttpResponse(response, body));
                stepBuilder.request(request);
                stepBuilder.responseTime(endTime - startTime);

                Response healthResponse = new Response();
                healthResponse.setStatus(response.statusCode());

                // If validation fail, store request and response data
                if (!stepBuilder.isSuccess()) {
                    request.setBody(step.getRequest().getBody());

                    if (step.getRequest().getHeaders() != null) {
                        HttpHeaders reqHeaders = new HttpHeaders();
                        step.getRequest().getHeaders().forEach(httpHeader -> reqHeaders
                                .put(httpHeader.getName(), Collections.singletonList(httpHeader.getValue())));
                        request.setHeaders(reqHeaders);
                    }

                    // Extract headers
                    HttpHeaders headers = new HttpHeaders();
                    response.headers().names().forEach(
                            headerName -> headers.put(headerName, response.headers().getAll(headerName)));
                    healthResponse.setHeaders(headers);

                    // Store body
                    healthResponse.setBody(body);
                }

                stepBuilder.response(healthResponse);

                // Append step stepBuilder
                healthBuilder.step(stepBuilder.build());

                report(healthBuilder.build());

                // Close client
                httpClient.close();
            }));

            healthRequest.exceptionHandler(event -> {
                long endTime = currentTimeMillis();

                EndpointStatus.StepBuilder stepBuilder = EndpointStatus.forStep(step.getName());
                stepBuilder.fail(event.getMessage());

                Response healthResponse = new Response();

                // Extract request information
                request.setBody(step.getRequest().getBody());
                if (step.getRequest().getHeaders() != null) {
                    HttpHeaders reqHeaders = new HttpHeaders();
                    step.getRequest().getHeaders().forEach(httpHeader -> reqHeaders.put(httpHeader.getName(),
                            Collections.singletonList(httpHeader.getValue())));
                    request.setHeaders(reqHeaders);
                }

                if (event instanceof ConnectTimeoutException) {
                    stepBuilder.fail(event.getMessage());
                    healthResponse.setStatus(HttpStatusCode.REQUEST_TIMEOUT_408);
                } else {
                    healthResponse.setStatus(HttpStatusCode.SERVICE_UNAVAILABLE_503);
                }

                Step result = stepBuilder.build();
                result.setResponse(healthResponse);
                result.setRequest(request);

                result.setResponseTime(endTime - startTime);

                // Append step result
                healthBuilder.step(result);

                report(healthBuilder.build());

                try {
                    // Close client
                    httpClient.close();
                } catch (IllegalStateException ise) {
                    // Do not take care about exception when closing client
                }
            });

            // Send request
            logger.debug("Execute health-check request: {}", healthRequest);
            if (step.getRequest().getBody() != null && !step.getRequest().getBody().isEmpty()) {
                healthRequest.end(step.getRequest().getBody());
            } else {
                healthRequest.end();
            }
        } catch (EndpointException ee) {
            logger.error("An error occurs while configuring the endpoint " + endpoint.getName()
                    + ". Healthcheck is skipped for this endpoint.", ee);
        } catch (Exception ex) {
            logger.error("An unexpected error occurs", ex);
        }
    }
}

From source file:io.gravitee.resource.oauth2.am.OAuth2AMResource.java

License:Apache License

@Override
public void introspect(String accessToken, Handler<OAuth2Response> responseHandler) {
    HttpClient httpClient = httpClients.computeIfAbsent(Vertx.currentContext(),
            context -> vertx.createHttpClient(httpClientOptions));

    logger.debug("Introspect access token by requesting {}", introspectionEndpointURI);

    HttpClientRequest request = httpClient.post(introspectionEndpointURI);

    request.headers().add(HttpHeaders.AUTHORIZATION, introspectionEndpointAuthorization);
    request.headers().add(HttpHeaders.ACCEPT, MediaType.APPLICATION_JSON);
    request.headers().add(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_FORM_URLENCODED);

    request.handler(response -> response.bodyHandler(buffer -> {
        logger.debug("AM Introspection endpoint returns a response with a {} status code",
                response.statusCode());/*  w  ww .jav a2 s  . co  m*/
        if (response.statusCode() == HttpStatusCode.OK_200) {
            // Introspection Response for AM v2 always returns HTTP 200
            // with an "active" boolean indicator of whether or not the presented token is currently active.
            if (configuration().getVersion() == OAuth2ResourceConfiguration.Version.V2_X) {
                // retrieve active indicator
                JsonObject jsonObject = buffer.toJsonObject();
                boolean active = jsonObject.getBoolean(INTROSPECTION_ACTIVE_INDICATOR, false);
                responseHandler.handle(new OAuth2Response(active,
                        (active) ? buffer.toString() : "{\"error\": \"Invalid Access Token\"}"));
            } else {
                responseHandler.handle(new OAuth2Response(true, buffer.toString()));
            }
        } else {
            responseHandler.handle(new OAuth2Response(false, buffer.toString()));
        }
    }));

    request.exceptionHandler(event -> {
        logger.error("An error occurs while checking access_token", event);
        responseHandler.handle(new OAuth2Response(false, event.getMessage()));
    });

    request.end("token=" + accessToken);
}

From source file:io.gravitee.resource.oauth2.generic.OAuth2GenericResource.java

License:Apache License

@Override
public void introspect(String accessToken, Handler<OAuth2Response> responseHandler) {
    HttpClient httpClient = httpClients.computeIfAbsent(Vertx.currentContext(),
            context -> vertx.createHttpClient(httpClientOptions));

    OAuth2ResourceConfiguration configuration = configuration();
    StringBuilder introspectionUriBuilder = new StringBuilder(introspectionEndpointURI);

    if (configuration.isTokenIsSuppliedByQueryParam()) {
        introspectionUriBuilder.append('?').append(configuration.getTokenQueryParamName()).append('=')
                .append(accessToken);//from  w  w  w  . j  a v  a  2 s . c o  m
    }

    String introspectionEndpointURI = introspectionUriBuilder.toString();
    logger.debug("Introspect access token by requesting {} [{}]", introspectionEndpointURI,
            configuration.getIntrospectionEndpointMethod());

    HttpMethod httpMethod = HttpMethod.valueOf(configuration.getIntrospectionEndpointMethod().toUpperCase());

    HttpClientRequest request = httpClient.requestAbs(httpMethod, introspectionEndpointURI);
    request.setTimeout(30000L);

    if (configuration().isUseClientAuthorizationHeader()) {
        String authorizationHeader = configuration.getClientAuthorizationHeaderName();
        String authorizationValue = configuration.getClientAuthorizationHeaderScheme().trim()
                + AUTHORIZATION_HEADER_SCHEME_SEPARATOR
                + Base64.getEncoder().encodeToString(
                        (configuration.getClientId() + AUTHORIZATION_HEADER_VALUE_BASE64_SEPARATOR
                                + configuration.getClientSecret()).getBytes());
        request.headers().add(authorizationHeader, authorizationValue);
        logger.debug("Set client authorization using HTTP header {} with value {}", authorizationHeader,
                authorizationValue);
    }

    // Set `Accept` header to ask for application/json content
    request.headers().add(HttpHeaders.ACCEPT, MediaType.APPLICATION_JSON);

    if (configuration.isTokenIsSuppliedByHttpHeader()) {
        request.headers().add(configuration.getTokenHeaderName(), accessToken);
    }

    request.handler(response -> response.bodyHandler(buffer -> {
        logger.debug("Introspection endpoint returns a response with a {} status code", response.statusCode());
        if (response.statusCode() == HttpStatusCode.OK_200) {
            // According to RFC 7662 : Note that a properly formed and authorized query for an inactive or
            // otherwise invalid token (or a token the protected resource is not
            // allowed to know about) is not considered an error response by this
            // specification.  In these cases, the authorization server MUST instead
            // respond with an introspection response with the "active" field set to
            // "false" as described in Section 2.2.
            String content = buffer.toString();

            try {
                JsonNode introspectNode = MAPPER.readTree(content);
                JsonNode activeNode = introspectNode.get("active");
                if (activeNode != null) {
                    boolean isActive = activeNode.asBoolean();
                    responseHandler.handle(new OAuth2Response(isActive, content));
                } else {
                    responseHandler.handle(new OAuth2Response(true, content));
                }
            } catch (IOException e) {
                logger.error("Unable to validate introspection endpoint payload: {}", content);
                responseHandler.handle(new OAuth2Response(false, content));
            }
        } else {
            responseHandler.handle(new OAuth2Response(false, buffer.toString()));
        }
    }));

    request.exceptionHandler(event -> {
        logger.error("An error occurs while checking OAuth2 token", event);
        responseHandler.handle(new OAuth2Response(false, event.getMessage()));
    });

    if (httpMethod == HttpMethod.POST && configuration.isTokenIsSuppliedByFormUrlEncoded()) {
        request.headers().add(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_FORM_URLENCODED);
        request.end(configuration.getTokenFormUrlEncodedName() + '=' + accessToken);
    } else {
        request.end();
    }
}

From source file:io.servicecomb.serviceregistry.client.http.RestUtils.java

License:Apache License

public static void httpDo(RequestContext requestContext, Handler<RestResponse> responseHandler) {
    HttpClientWithContext vertxHttpClient = HttpClientPool.INSTANCE.getClient();
    vertxHttpClient.runOnContext(httpClient -> {
        IpPort ipPort = requestContext.getIpPort();
        HttpMethod httpMethod = requestContext.getMethod();
        RequestParam requestParam = requestContext.getParams();

        if (ipPort == null) {
            LOGGER.error("request address is null");
            responseHandler.handle(new RestResponse(requestContext, null));
            return;
        }/*from  w w w.ja va2s . co  m*/

        // query params
        StringBuilder url = new StringBuilder(requestContext.getUri());
        String queryParams = requestParam.getQueryParams();
        if (!queryParams.isEmpty()) {
            url.append(url.lastIndexOf("?") > 0 ? "&" : "?").append(queryParams);
        }

        HttpClientRequest httpClientRequest = httpClient.request(httpMethod, ipPort.getPort(),
                ipPort.getHostOrIp(), url.toString(), response -> {
                    responseHandler.handle(new RestResponse(requestContext, response));
                });

        httpClientRequest.setTimeout(ServiceRegistryConfig.INSTANCE.getRequestTimeout()).exceptionHandler(e -> {
            LOGGER.error("{} {} fail, endpoint is {}:{}, message: {}", httpMethod, url.toString(),
                    ipPort.getHostOrIp(), ipPort.getPort(), e.getMessage());
            responseHandler.handle(new RestResponse(requestContext, null));
        });

        //headers
        Map<String, String> headers = defaultHeaders();
        httpClientRequest.headers().addAll(headers);

        if (requestParam.getHeaders() != null && requestParam.getHeaders().size() > 0) {
            headers.putAll(requestParam.getHeaders());
            for (Map.Entry<String, String> header : requestParam.getHeaders().entrySet()) {
                httpClientRequest.putHeader(header.getKey(), header.getValue());
            }
        }

        // cookies header
        if (requestParam.getCookies() != null && requestParam.getCookies().size() > 0) {
            StringBuilder stringBuilder = new StringBuilder();
            for (Map.Entry<String, String> cookie : requestParam.getCookies().entrySet()) {
                stringBuilder.append(cookie.getKey()).append("=").append(cookie.getValue()).append("; ");
            }
            httpClientRequest.putHeader("Cookie", stringBuilder.toString());
            headers.put("Cookie", stringBuilder.toString());
        }

        //SignAuth
        SignRequest signReq = createSignRequest(requestContext.getMethod().toString(),
                requestContext.getIpPort(), requestContext.getParams(), url.toString(), headers);
        httpClientRequest.headers().addAll(getSignAuthHeaders(signReq));

        // body
        if (httpMethod != HttpMethod.GET && requestParam.getBody() != null
                && requestParam.getBody().length > 0) {
            httpClientRequest.end(Buffer.buffer(requestParam.getBody()));
        } else {
            httpClientRequest.end();
        }
    });
}

From source file:org.apache.servicecomb.serviceregistry.client.http.RestUtils.java

License:Apache License

public static void httpDo(long timeout, RequestContext requestContext, Handler<RestResponse> responseHandler) {
    HttpClientWithContext vertxHttpClient = HttpClientPool.INSTANCE.getClient();
    vertxHttpClient.runOnContext(httpClient -> {
        IpPort ipPort = requestContext.getIpPort();
        HttpMethod httpMethod = requestContext.getMethod();
        RequestParam requestParam = requestContext.getParams();

        if (ipPort == null) {
            LOGGER.error("request address is null");
            responseHandler.handle(new RestResponse(requestContext, null));
            return;
        }/*from ww  w. j a  va2  s . c om*/

        // query params
        StringBuilder url = new StringBuilder(requestContext.getUri());
        String queryParams = requestParam.getQueryParams();
        if (!queryParams.isEmpty()) {
            url.append(url.lastIndexOf("?") > 0 ? "&" : "?").append(queryParams);
        }

        HttpClientRequest httpClientRequest = httpClient.request(httpMethod, ipPort.getPort(),
                ipPort.getHostOrIp(), url.toString(), response -> {
                    responseHandler.handle(new RestResponse(requestContext, response));
                });

        httpClientRequest.setTimeout(timeout).exceptionHandler(e -> {
            LOGGER.error("{} {} fail, endpoint is {}:{}, message: {}", httpMethod, url.toString(),
                    ipPort.getHostOrIp(), ipPort.getPort(), e.getMessage());
            responseHandler.handle(new RestResponse(requestContext, null));
        });

        //headers
        Map<String, String> headers = defaultHeaders();
        httpClientRequest.headers().addAll(headers);

        if (requestParam.getHeaders() != null && requestParam.getHeaders().size() > 0) {
            headers.putAll(requestParam.getHeaders());
            for (Map.Entry<String, String> header : requestParam.getHeaders().entrySet()) {
                httpClientRequest.putHeader(header.getKey(), header.getValue());
            }
        }

        // cookies header
        if (requestParam.getCookies() != null && requestParam.getCookies().size() > 0) {
            StringBuilder stringBuilder = new StringBuilder();
            for (Map.Entry<String, String> cookie : requestParam.getCookies().entrySet()) {
                stringBuilder.append(cookie.getKey()).append("=").append(cookie.getValue()).append("; ");
            }
            httpClientRequest.putHeader("Cookie", stringBuilder.toString());
            headers.put("Cookie", stringBuilder.toString());
        }

        //SignAuth
        SignRequest signReq = createSignRequest(requestContext.getMethod().toString(),
                requestContext.getIpPort(), requestContext.getParams(), url.toString(), headers);
        httpClientRequest.headers().addAll(getSignAuthHeaders(signReq));

        // body
        if (httpMethod != HttpMethod.GET && requestParam.getBody() != null
                && requestParam.getBody().length > 0) {
            httpClientRequest.end(Buffer.buffer(requestParam.getBody()));
        } else {
            httpClientRequest.end();
        }
    });
}

From source file:org.entcore.cas.http.WrappedVertxHttpClient.java

License:Open Source License

@Override
public void post(String uri, String body, final Handler<ClientResponse> handler) {
    HttpClientRequest req = httpClient.post(uri, new io.vertx.core.Handler<HttpClientResponse>() {
        @Override/*from w w w  . j a  v a 2  s  . com*/
        public void handle(final HttpClientResponse response) {
            handler.handle(new ClientResponse() {
                @Override
                public int getStatusCode() {
                    return response.statusCode();
                }
            });
            httpClient.close();
        }
    });
    req.end(body);
}