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

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

Introduction

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

Prototype

@GenIgnore(GenIgnore.PERMITTED_TYPE)
@Fluent
HttpClientRequest putHeader(CharSequence name, Iterable<CharSequence> values);

Source Link

Document

Like #putHeader(String,Iterable) but using CharSequence

Usage

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

License:Apache License

/**
 * Perform the actual rest call// w w w. j  a v  a 2 s. co m
 *
 * @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:com.navercorp.pinpoint.plugin.vertx.HttpClientRequestClientHeaderAdaptor.java

License:Apache License

@Override
public void setHeader(HttpClientRequest httpClientRequest, String name, String value) {
    httpClientRequest.putHeader(name, value);
    if (isDebug) {
        logger.debug("Set header {}={}", name, value);
    }/*from w  ww  .  ja  v  a  2  s.  co m*/
}

From source file:com.navercorp.pinpoint.plugin.vertx.interceptor.HttpClientImplDoRequestInterceptor.java

License:Apache License

@Override
public void after(Object target, Object[] args, Object result, Throwable throwable) {
    if (isDebug) {
        logger.afterInterceptor(target, args, result, throwable);
    }//  w ww. j  a va  2  s. c  o  m

    final Trace trace = traceContext.currentTraceObject();
    if (trace == null) {
        return;
    }

    HttpClientRequest request = null;
    if (validate(result)) {
        request = (HttpClientRequest) result;
    }

    if (!trace.canSampled()) {
        if (request != null) {
            request.putHeader(Header.HTTP_SAMPLED.toString(), SamplingFlagUtils.SAMPLING_RATE_FALSE);
        }
        return;
    }

    try {
        final SpanEventRecorder recorder = trace.currentSpanEventRecorder();
        recorder.recordApi(methodDescriptor);
        recorder.recordException(throwable);
        recorder.recordServiceType(VertxConstants.VERTX_HTTP_CLIENT_INTERNAL);

        final String hostAndPort = toHostAndPort(args);
        if (hostAndPort != null) {
            recorder.recordAttribute(AnnotationKey.HTTP_INTERNAL_DISPLAY, hostAndPort);
            if (isDebug) {
                logger.debug("Set hostAndPort {}", hostAndPort);
            }
        }

        if (request != null) {
            // make asynchronous trace-id
            final AsyncContext asyncContext = recorder.recordNextAsyncContext();
            ((AsyncContextAccessor) request)._$PINPOINT$_setAsyncContext(asyncContext);
            if (isDebug) {
                logger.debug("Set asyncContext {}", asyncContext);
            }
        }
    } finally {
        trace.traceBlockEnd();
    }
}

From source file:examples.HTTPExamples.java

License:Open Source License

public void example34(Vertx vertx, String body) {
    HttpClient client = vertx.createHttpClient();

    HttpClientRequest request = client.post("some-uri", response -> {
        System.out.println("Received response with status code " + response.statusCode());
    });/*from   w w  w  .j a  v  a 2 s.co m*/

    // Now do stuff with the request
    request.putHeader("content-length", "1000");
    request.putHeader("content-type", "text/plain");
    request.write(body);

    // Make sure the request is ended when you're done with it
    request.end();

    // Or fluently:

    client.post("some-uri", response -> {
        System.out.println("Received response with status code " + response.statusCode());
    }).putHeader("content-length", "1000").putHeader("content-type", "text/plain").write(body).end();

    // Or event more simply:

    client.post("some-uri", response -> {
        System.out.println("Received response with status code " + response.statusCode());
    }).putHeader("content-type", "text/plain").end(body);

}

From source file:examples.HTTPExamples.java

License:Open Source License

public void example38(HttpClientRequest request) {

    // Write some headers using the putHeader method

    request.putHeader("content-type", "application/json").putHeader("other-header", "foo");

}

From source file:examples.HTTPExamples.java

License:Open Source License

public void example50(HttpClient client) {

    HttpClientRequest request = client.put("some-uri", response -> {
        System.out.println("Received response with status code " + response.statusCode());
    });/*from  ww w  .j  av  a 2s  .c o  m*/

    request.putHeader("Expect", "100-Continue");

    request.continueHandler(v -> {
        // OK to send rest of body
        request.write("Some data");
        request.write("Some more data");
        request.end();
    });
}

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

License:Apache License

@Override
public void sendHttpRequest(final HttpRequest request) {

    checkClosed();//  ww  w.j  a  va 2s . c  o 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.flowly.core.security.OAuth2.java

License:Open Source License

/**
 * Include an Authorization header to the request with the value of Basic and bearer token credentials.
 * Add request body for OAuth2./*from  w w w .ja v  a  2  s  . c o  m*/
 *
 * @param request the https client request to which the authorization header is to be added.
 * @param bearerTokenCredentials Base64 encoded bearer token credentials for OAuth2.
 */
public static void prepareOAuthBearerTokenRequest(HttpClientRequest request, String bearerTokenCredentials) {
    String body = "grant_type=client_credentials";
    request.putHeader("Authorization", "Basic " + bearerTokenCredentials);
    request.putHeader("Content-Type", "application/x-www-form-urlencoded;charset=UTF-8");
    request.putHeader("Content-Length", "" + body.length());
    request.write(body);
}

From source file:io.gravitee.gateway.http.vertx.VertxHttpClient.java

License:Apache License

private void copyRequestHeaders(HttpHeaders headers, HttpClientRequest httpClientRequest, String host) {
    for (Map.Entry<String, List<String>> headerValues : headers.entrySet()) {
        String headerName = headerValues.getKey();
        String lowerHeaderName = headerName.toLowerCase(Locale.ENGLISH);

        // Remove hop-by-hop headers.
        if (HOP_HEADERS.contains(lowerHeaderName)) {
            continue;
        }//from  w w w . j a v a2 s.c  o  m

        httpClientRequest.putHeader(headerName, headerValues.getValue());
    }

    httpClientRequest.putHeader(HttpHeaders.HOST, host);
}

From source file:io.helixservice.feature.restclient.RestRequest.java

License:Open Source License

/**
 * Execute the request, with the expected response body marshaled
 * to a specific object type./*from  w w w. jav a  2s .  c  o m*/
 *
 * @param responseType Type we expect the response to be marshaled to
 * @return RestResponse fluent interface
 * @throws SuspendExecution For Vert.x Sync
 */
public <T> RestResponse<T> asObject(Class<T> responseType) throws SuspendExecution {
    try {
        // Apply Params & Url Vars
        String modifiedUrlPath = addParameters(replaceUrlVars(urlPath));

        // Do request
        HttpClientRequest request;
        if (useDefaultHostAndPort) {
            request = httpClient.get().request(io.vertx.core.http.HttpMethod.valueOf(method.name()),
                    modifiedUrlPath);
        } else {
            request = httpClient.get().requestAbs(io.vertx.core.http.HttpMethod.valueOf(method.name()),
                    modifiedUrlPath);
        }

        // Set timeout, if requested
        if (timeoutInMs != null) {
            request.setTimeout(timeoutInMs);
        }

        // With headers
        request.headers().addAll(VertxTypeConverter.toVertxMultiMap(headers));

        // Write body if we need to
        Buffer body = Buffer.buffer();
        if (requestBody.isPresent()) {
            request.setChunked(true);
            Message message = marshallerSupplier.get().marshal(requestBody);

            List<String> contentTypes = message.getContentTypes();
            if (contentTypes != null && contentTypes.size() > 0) {
                request.putHeader("Content-Type", contentTypes);
            }

            body = body.appendBytes(message.getBody());
        }

        // Wait for response with Vert.x Sync
        HttpClientResponse httpClientResponse = getHttpClientResponse(request, body);
        Buffer bodyBuffer = getBuffer(httpClientResponse);

        return new RestResponse<>(httpClientResponse, bodyBuffer, marshallerSupplier, responseType);
    } catch (URISyntaxException | UnsupportedEncodingException e) {
        throw new IllegalArgumentException("Unable to parse urlPath=" + urlPath, e);
    }
}