Search in sources :

Example 1 with Buffer

use of io.vertx.reactivex.core.buffer.Buffer in project vertx-examples by vert-x3.

the class Client method start.

@Override
public void start() throws Exception {
    HttpClient client = vertx.createHttpClient();
    HttpClientRequest req = client.request(HttpMethod.GET, 8080, "localhost", "/");
    req.toFlowable().flatMap(resp -> {
        if (resp.statusCode() != 200) {
            throw new RuntimeException("Wrong status code " + resp.statusCode());
        }
        return Flowable.just(Buffer.buffer()).mergeWith(resp.toFlowable());
    }).reduce(Buffer::appendBuffer).map(buffer -> buffer.toString("UTF-8")).subscribe(data -> System.out.println("Server content " + data));
    // End request
    req.end();
}
Also used : HttpClientRequest(io.vertx.reactivex.core.http.HttpClientRequest) Flowable(io.reactivex.Flowable) HttpMethod(io.vertx.core.http.HttpMethod) HttpClient(io.vertx.reactivex.core.http.HttpClient) AbstractVerticle(io.vertx.reactivex.core.AbstractVerticle) Runner(io.vertx.example.util.Runner) Buffer(io.vertx.reactivex.core.buffer.Buffer) Buffer(io.vertx.reactivex.core.buffer.Buffer) HttpClientRequest(io.vertx.reactivex.core.http.HttpClientRequest) HttpClient(io.vertx.reactivex.core.http.HttpClient)

Example 2 with Buffer

use of io.vertx.reactivex.core.buffer.Buffer in project knotx by Cognifide.

the class HttpClientFacade method callService.

private Single<HttpResponse<Buffer>> callService(Pair<ClientRequest, ServiceMetadata> serviceData, HttpMethod method) {
    final Single<HttpResponse<Buffer>> httpResponse;
    final ClientRequest serviceRequest = serviceData.getLeft();
    final ServiceMetadata serviceMetadata = serviceData.getRight();
    final HttpRequest<Buffer> request = webClient.request(method, serviceMetadata.getPort(), serviceMetadata.getDomain(), serviceRequest.getPath());
    updateRequestQueryParams(request, serviceMetadata);
    updateRequestHeaders(request, serviceRequest, serviceMetadata);
    overrideRequestHeaders(request, serviceMetadata);
    if (!serviceRequest.getFormAttributes().isEmpty()) {
        httpResponse = request.rxSendForm(serviceRequest.getFormAttributes());
    } else {
        httpResponse = request.rxSend();
    }
    return httpResponse;
}
Also used : Buffer(io.vertx.reactivex.core.buffer.Buffer) HttpResponse(io.vertx.reactivex.ext.web.client.HttpResponse) ClientRequest(io.knotx.dataobjects.ClientRequest)

Example 3 with Buffer

use of io.vertx.reactivex.core.buffer.Buffer in project knotx by Cognifide.

the class HttpClientFacade method updateRequestHeaders.

private void updateRequestHeaders(HttpRequest<Buffer> request, ClientRequest serviceRequest, ServiceMetadata serviceMetadata) {
    MultiMap filteredHeaders = getFilteredHeaders(serviceRequest.getHeaders(), serviceMetadata.getAllowedRequestHeaderPatterns());
    filteredHeaders.names().forEach(headerName -> filteredHeaders.getAll(headerName).forEach(value -> request.headers().add(headerName, value)));
    if (customRequestHeader.containsKey("name") && customRequestHeader.containsKey("value")) {
        request.headers().set(customRequestHeader.getString("name"), customRequestHeader.getString("value"));
    }
}
Also used : HttpResponse(io.vertx.reactivex.ext.web.client.HttpResponse) UnsupportedServiceException(io.knotx.adapter.common.exception.UnsupportedServiceException) MultiMapCollector(io.knotx.http.MultiMapCollector) Single(io.reactivex.Single) LoggerFactory(io.vertx.core.logging.LoggerFactory) WebClient(io.vertx.reactivex.ext.web.client.WebClient) AdapterServiceContractException(io.knotx.adapter.common.exception.AdapterServiceContractException) ClientResponse(io.knotx.dataobjects.ClientResponse) DataObjectsUtil(io.knotx.util.DataObjectsUtil) MultiMap(io.vertx.reactivex.core.MultiMap) List(java.util.List) AdapterRequest(io.knotx.dataobjects.AdapterRequest) Pair(org.apache.commons.lang3.tuple.Pair) UriTransformer(io.knotx.adapter.common.placeholders.UriTransformer) AllowedHeadersFilter(io.knotx.http.AllowedHeadersFilter) HttpMethod(io.vertx.core.http.HttpMethod) ClientRequest(io.knotx.dataobjects.ClientRequest) HttpRequest(io.vertx.reactivex.ext.web.client.HttpRequest) Optional(java.util.Optional) JsonObject(io.vertx.core.json.JsonObject) Pattern(java.util.regex.Pattern) Logger(io.vertx.core.logging.Logger) Buffer(io.vertx.reactivex.core.buffer.Buffer) MultiMap(io.vertx.reactivex.core.MultiMap)

Example 4 with Buffer

use of io.vertx.reactivex.core.buffer.Buffer in project NetDiscovery by fengzhizi715.

the class VertxDownloader method download.

public Maybe<Response> download(Request request) {
    WebClientOptions options = initWebClientOptions(request);
    webClient = WebClient.create(vertx, options);
    HttpRequest<Buffer> httpRequest = null;
    if (request.getHttpMethod() == HttpMethod.GET) {
        if ("http".equals(request.getUrlParser().getProtocol())) {
            httpRequest = webClient.getAbs(request.getUrl());
        } else if ("https".equals(request.getUrlParser().getProtocol())) {
            httpRequest = webClient.get(443, request.getUrlParser().getHost(), Preconditions.isNotBlank(request.getUrlParser().getQuery()) ? request.getUrlParser().getPath() + "?" + request.getUrlParser().getQuery() : request.getUrlParser().getPath()).ssl(true);
        }
    } else if (request.getHttpMethod() == HttpMethod.POST) {
        if ("http".equals(request.getUrlParser().getProtocol())) {
            httpRequest = webClient.postAbs(request.getUrl());
        } else if ("https".equals(request.getUrlParser().getProtocol())) {
            httpRequest = webClient.post(443, request.getUrlParser().getHost(), Preconditions.isNotBlank(request.getUrlParser().getQuery()) ? request.getUrlParser().getPath() + "?" + request.getUrlParser().getQuery() : request.getUrlParser().getPath()).ssl(true);
        }
    }
    // 设置请求头header
    if (Preconditions.isNotBlank(header)) {
        for (Map.Entry<String, String> entry : header.entrySet()) {
            httpRequest.putHeader(entry.getKey(), entry.getValue());
        }
    }
    // 针对post请求,需要对header添加一些信息
    if (request.getHttpMethod() == HttpMethod.POST) {
        if (Preconditions.isNotBlank(request.getHttpRequestBody()) && Preconditions.isNotBlank(request.getHttpRequestBody().getContentType())) {
            httpRequest.putHeader("Content-type", request.getHttpRequestBody().getContentType());
        }
    }
    String charset = null;
    if (Preconditions.isNotBlank(request.getCharset())) {
        charset = request.getCharset();
    } else {
        charset = Constant.UTF_8;
    }
    HttpRequest<String> stringHttpRequest = httpRequest.as(BodyCodec.string(charset));
    Single<HttpResponse<String>> httpResponseSingle = null;
    if (request.getHttpMethod() == HttpMethod.GET) {
        httpResponseSingle = stringHttpRequest.rxSend();
    } else if (request.getHttpMethod() == HttpMethod.POST) {
        if (Preconditions.isNotBlank(request.getHttpRequestBody())) {
            Buffer buffer = Buffer.buffer();
            buffer.getDelegate().appendBytes(request.getHttpRequestBody().getBody());
            httpResponseSingle = stringHttpRequest.rxSendBuffer(buffer);
        } else {
            httpResponseSingle = stringHttpRequest.rxSend();
        }
    }
    return httpResponseSingle.toMaybe().map(new Function<HttpResponse<String>, Response>() {

        @Override
        public Response apply(HttpResponse<String> stringHttpResponse) throws Exception {
            String html = stringHttpResponse.body();
            Response response = new Response();
            response.setContent(html.getBytes());
            response.setStatusCode(stringHttpResponse.statusCode());
            response.setContentType(stringHttpResponse.getHeader("Content-Type"));
            if (request.isSaveCookie()) {
                // save cookies
                if (Preconditions.isNotBlank(stringHttpResponse.cookies())) {
                    CookieGroup cookieGroup = CookieManager.getInsatance().getCookieGroup(request.getUrlParser().getHost());
                    if (cookieGroup == null) {
                        cookieGroup = new CookieGroup(request.getUrlParser().getHost());
                        for (String cookieStr : stringHttpResponse.cookies()) {
                            String[] segs = cookieStr.split(";");
                            if (Preconditions.isNotBlank(segs)) {
                                for (String seg : segs) {
                                    String[] pairs = seg.trim().split("\\=");
                                    if (pairs.length == 2) {
                                        cookieSet.add(new Cookie(pairs[0], pairs[1]));
                                    }
                                }
                            }
                        }
                        cookieGroup.putAllCookies(cookieSet);
                        CookieManager.getInsatance().addCookieGroup(cookieGroup);
                    } else {
                        for (String cookieStr : stringHttpResponse.cookies()) {
                            String[] segs = cookieStr.split(";");
                            if (Preconditions.isNotBlank(segs)) {
                                for (String seg : segs) {
                                    String[] pairs = seg.trim().split("\\=");
                                    if (pairs.length == 2) {
                                        cookieSet.add(new Cookie(pairs[0], pairs[1]));
                                    }
                                }
                            }
                        }
                        cookieGroup.putAllCookies(cookieSet);
                    }
                }
            }
            return response;
        }
    });
}
Also used : Buffer(io.vertx.reactivex.core.buffer.Buffer) Cookie(com.cv4j.netdiscovery.core.cookies.Cookie) WebClientOptions(io.vertx.ext.web.client.WebClientOptions) HttpResponse(io.vertx.reactivex.ext.web.client.HttpResponse) HttpResponse(io.vertx.reactivex.ext.web.client.HttpResponse) Response(com.cv4j.netdiscovery.core.domain.Response) CookieGroup(com.cv4j.netdiscovery.core.cookies.CookieGroup) Map(java.util.Map)

Aggregations

Buffer (io.vertx.reactivex.core.buffer.Buffer)4 HttpResponse (io.vertx.reactivex.ext.web.client.HttpResponse)3 ClientRequest (io.knotx.dataobjects.ClientRequest)2 HttpMethod (io.vertx.core.http.HttpMethod)2 Cookie (com.cv4j.netdiscovery.core.cookies.Cookie)1 CookieGroup (com.cv4j.netdiscovery.core.cookies.CookieGroup)1 Response (com.cv4j.netdiscovery.core.domain.Response)1 AdapterServiceContractException (io.knotx.adapter.common.exception.AdapterServiceContractException)1 UnsupportedServiceException (io.knotx.adapter.common.exception.UnsupportedServiceException)1 UriTransformer (io.knotx.adapter.common.placeholders.UriTransformer)1 AdapterRequest (io.knotx.dataobjects.AdapterRequest)1 ClientResponse (io.knotx.dataobjects.ClientResponse)1 AllowedHeadersFilter (io.knotx.http.AllowedHeadersFilter)1 MultiMapCollector (io.knotx.http.MultiMapCollector)1 DataObjectsUtil (io.knotx.util.DataObjectsUtil)1 Flowable (io.reactivex.Flowable)1 Single (io.reactivex.Single)1 JsonObject (io.vertx.core.json.JsonObject)1 Logger (io.vertx.core.logging.Logger)1 LoggerFactory (io.vertx.core.logging.LoggerFactory)1