reactor.netty.http.client.HttpClient.headers()方法的使用及代码示例

x33g5p2x  于2022-01-20 转载在 其他  
字(10.3k)|赞(0)|评价(0)|浏览(251)

本文整理了Java中reactor.netty.http.client.HttpClient.headers()方法的一些代码示例,展示了HttpClient.headers()的具体用法。这些代码示例主要来源于Github/Stackoverflow/Maven等平台,是从一些精选项目中提取出来的代码,具有较强的参考意义,能在一定程度帮忙到你。HttpClient.headers()方法的具体详情如下:
包路径:reactor.netty.http.client.HttpClient
类名称:HttpClient
方法名:headers

HttpClient.headers介绍

[英]Apply headers configuration.
[中]应用标题配置。

代码示例

代码示例来源:origin: spring-projects/spring-framework

@Override
public Mono<Void> execute(URI url, HttpHeaders requestHeaders, WebSocketHandler handler) {
  return getHttpClient()
      .headers(nettyHeaders -> setNettyHeaders(requestHeaders, nettyHeaders))
      .websocket(StringUtils.collectionToCommaDelimitedString(handler.getSubProtocols()))
      .uri(url.toString())
      .handle((inbound, outbound) -> {
        HttpHeaders responseHeaders = toHttpHeaders(inbound);
        String protocol = responseHeaders.getFirst("Sec-WebSocket-Protocol");
        HandshakeInfo info = new HandshakeInfo(url, responseHeaders, Mono.empty(), protocol);
        NettyDataBufferFactory factory = new NettyDataBufferFactory(outbound.alloc());
        WebSocketSession session = new ReactorNettyWebSocketSession(inbound, outbound, info, factory);
        if (logger.isDebugEnabled()) {
          logger.debug("Started session '" + session.getId() + "' for " + url);
        }
        return handler.handle(session);
      })
      .doOnRequest(n -> {
        if (logger.isDebugEnabled()) {
          logger.debug("Connecting to " + url);
        }
      })
      .next();
}

代码示例来源:origin: rabbitmq/hop

private Mono<HttpResponse> doDelete(Consumer<? super HttpHeaders> headerBuilder, String... pathSegments) {
  return client.headersWhen(authorizedHeader())
    .headers(headerBuilder)
    .delete()
    .uri(uri(pathSegments))
    .response()
    .doOnNext(applyResponseCallback())
    .map(ReactorNettyClient::toHttpResponse);
}

代码示例来源:origin: rsocket/rsocket-java

@Override
public Mono<DuplexConnection> connect() {
 return client
   .headers(headers -> transportHeaders.get().forEach(headers::set))
   .websocket()
   .uri(path)
   .connect()
   .map(WebsocketDuplexConnection::new);
}

代码示例来源:origin: com.rabbitmq/http-client

private Mono<HttpResponse> doDelete(Consumer<? super HttpHeaders> headerBuilder, String... pathSegments) {
  return client.headersWhen(authorizedHeader())
    .headers(headerBuilder)
    .delete()
    .uri(uri(pathSegments))
    .response()
    .doOnNext(applyResponseCallback())
    .map(ReactorNettyClient::toHttpResponse);
}

代码示例来源:origin: reactor/reactor-netty

/**
 * Specifies whether GZip compression/websocket compression
 * extension is enabled.
 *
 * @param compressionEnabled if true GZip compression/websocket compression extension
 *                              is enabled otherwise disabled (default: false)
 * @return a new {@link HttpClient}
 */
public final HttpClient compress(boolean compressionEnabled) {
  if (compressionEnabled) {
    return tcpConfiguration(COMPRESS_ATTR_CONFIG).headers(COMPRESS_HEADERS);
  }
  else {
    return tcpConfiguration(COMPRESS_ATTR_DISABLE).headers(COMPRESS_HEADERS_DISABLE);
  }
}

代码示例来源:origin: com.rabbitmq/http-client

private Mono<HttpResponse> doPut(String... pathSegments) {
  return client.headersWhen(authorizedHeader())
    .headers(JSON_HEADER)
    .chunkedTransfer(false)
    .put()
    .uri(uri(pathSegments))
    .response()
    .doOnNext(applyResponseCallback())
    .map(ReactorNettyClient::toHttpResponse);
}

代码示例来源:origin: io.projectreactor.netty/reactor-netty

/**
 * Specifies whether GZip compression/websocket compression
 * extension is enabled.
 *
 * @param compressionEnabled if true GZip compression/websocket compression extension
 *                              is enabled otherwise disabled (default: false)
 * @return a new {@link HttpClient}
 */
public final HttpClient compress(boolean compressionEnabled) {
  if (compressionEnabled) {
    return tcpConfiguration(COMPRESS_ATTR_CONFIG).headers(COMPRESS_HEADERS);
  }
  else {
    return tcpConfiguration(COMPRESS_ATTR_DISABLE).headers(COMPRESS_HEADERS_DISABLE);
  }
}

代码示例来源:origin: rabbitmq/hop

private Mono<HttpResponse> doPut(String... pathSegments) {
  return client.headersWhen(authorizedHeader())
    .headers(JSON_HEADER)
    .chunkedTransfer(false)
    .put()
    .uri(uri(pathSegments))
    .response()
    .doOnNext(applyResponseCallback())
    .map(ReactorNettyClient::toHttpResponse);
}

代码示例来源:origin: io.rsocket/rsocket-transport-netty

@Override
public Mono<DuplexConnection> connect() {
 return client
   .headers(headers -> transportHeaders.get().forEach(headers::set))
   .websocket()
   .uri(path)
   .connect()
   .map(WebsocketDuplexConnection::new);
}

代码示例来源:origin: rabbitmq/hop

private Mono<HttpResponse> doPost(Object body, String... pathSegments) {
  return client.headersWhen(authorizedHeader())
    .headers(JSON_HEADER)
    .chunkedTransfer(false)
    .post()
    .uri(uri(pathSegments))
    .send(bodyPublisher(body))
    .response()
    .doOnNext(applyResponseCallback())
    .map(ReactorNettyClient::toHttpResponse);
}

代码示例来源:origin: reactor/reactor-netty

@Test
public void contentHeader() {
  ConnectionProvider fixed = ConnectionProvider.fixed("test", 1);
  HttpClient client =
      HttpClient.create(fixed)
           .wiretap(true)
           .headers(h -> h.add("content-length", "1"));
  HttpResponseStatus r =
      client.request(HttpMethod.GET)
         .uri("http://google.com")
         .send(ByteBufFlux.fromString(Mono.just(" ")))
         .responseSingle((res, buf) -> Mono.just(res.status()))
         .block(Duration.ofSeconds(30));
  client.request(HttpMethod.GET)
     .uri("http://google.com")
     .send(ByteBufFlux.fromString(Mono.just(" ")))
     .responseSingle((res, buf) -> Mono.just(res.status()))
     .block(Duration.ofSeconds(30));
  Assert.assertEquals(r, HttpResponseStatus.BAD_REQUEST);
  fixed.dispose();
}

代码示例来源:origin: com.rabbitmq/http-client

private Mono<HttpResponse> doPost(Object body, String... pathSegments) {
  return client.headersWhen(authorizedHeader())
    .headers(JSON_HEADER)
    .chunkedTransfer(false)
    .post()
    .uri(uri(pathSegments))
    .send(bodyPublisher(body))
    .response()
    .doOnNext(applyResponseCallback())
    .map(ReactorNettyClient::toHttpResponse);
}

代码示例来源:origin: reactor/reactor-netty

@Test
public void simpleSubprotocolServerSupported() {
  httpServer = HttpServer.create()
              .port(0)
              .handle((in, out) -> out.sendWebsocket("SUBPROTOCOL",
                  (i, o) -> o.sendString(Mono.just("test"))))
              .wiretap(true)
              .bindNow();
  String res = Objects.requireNonNull(
      HttpClient.create()
           .port(httpServer.address()
                   .getPort())
           .wiretap(true)
           .headers(h -> h.add("Authorization", auth))
           .websocket("SUBPROTOCOL,OTHER")
           .uri("/test")
           .handle((i, o) -> i.receive().asString())
           .log()
           .collectList()
           .block(Duration.ofSeconds(30))).get(0);
  Assert.assertThat(res, is("test"));
}

代码示例来源:origin: reactor/reactor-netty

@Test
public void anySubprotocolSelectsFirstClientProvided() {
  httpServer = HttpServer.create()
              .port(0)
              .handle((in, out) -> out.sendWebsocket("proto2,*", (i, o) -> o.sendString(
                  Mono.just("SERVER:" + o.selectedSubprotocol()))))
              .wiretap(true)
              .bindNow();
  String res = Objects.requireNonNull(
      HttpClient.create()
           .port(httpServer.address().getPort())
           .headers(h -> h.add("Authorization", auth))
           .websocket("proto1, proto2")
           .uri("/test")
           .handle((in, out) -> in.receive()
                       .asString()
                       .map(srv -> "CLIENT:" + in.selectedSubprotocol() + "-" + srv))
           .log()
           .collectList()
           .block(Duration.ofSeconds(30))).get(0);
  Assert.assertThat(res, is("CLIENT:proto1-SERVER:proto1"));
}

代码示例来源:origin: reactor/reactor-netty

@Test
public void noSubprotocolSelected() {
  httpServer = HttpServer.create()
              .port(0)
              .handle((in, out) -> out.sendWebsocket((i, o) -> o.sendString(
                  Mono.just("SERVER:" + o.selectedSubprotocol()))))
              .wiretap(true)
              .bindNow();
  String res = Objects.requireNonNull(
      HttpClient.create()
           .port(httpServer.address().getPort())
           .headers(h -> h.add("Authorization", auth))
           .websocket()
           .uri("/test")
           .handle((in, out) -> in.receive()
                       .asString()
                       .map(srv -> "CLIENT:" + in.selectedSubprotocol() + "-" + srv))
           .log()
           .collectList()
           .block(Duration.ofSeconds(30))).get(0);
  Assert.assertThat(res, is("CLIENT:null-SERVER:null"));
}

代码示例来源:origin: reactor/reactor-netty

@Test
public void simpleTest() {
  httpServer = HttpServer.create()
              .port(0)
              .handle((in, out) -> out.sendWebsocket((i, o) -> o.sendString(Mono.just("test"))))
              .wiretap(true)
              .bindNow();
  String res = Objects.requireNonNull(
      HttpClient.create()
           .port(httpServer.address().getPort())
           .wiretap(true)
           .headers(h -> h.add("Authorization", auth))
           .websocket()
           .uri("/test")
           .handle((i, o) -> i.receive().asString())
           .log("client")
           .collectList()
           .block()).get(0);
  Assert.assertThat(res, is("test"));
}

代码示例来源:origin: reactor/reactor-netty

private Mono<Void> proxy(HttpServerRequest request, HttpServerResponse response) {
  return HttpClient.create()
           .wiretap(true)
           .headers(h -> h.add(filterRequestHeaders(request.requestHeaders())))
           .get()
           .uri(URI.create("http://localhost:" + CONTENT_SERVER_PORT +
                   "/" + request.path())
               .toString())
           .response((targetResponse, buf) -> response.headers(filterResponseHeaders(targetResponse.responseHeaders()))
                            .send(buf.retain())
                            .then())
           .then();
}

代码示例来源:origin: reactor/reactor-netty

@Test
public void simpleSubprotocolServerNoSubprotocol() {
  httpServer = HttpServer.create()
              .port(0)
              .handle((in, out) -> out.sendWebsocket((i, o) -> o.sendString(
                        Mono.just("test"))))
              .wiretap(true)
              .bindNow();
  StepVerifier.create(
      HttpClient.create()
           .port(httpServer.address().getPort())
           .headers(h -> h.add("Authorization", auth))
           .websocket("SUBPROTOCOL,OTHER")
           .uri("/test")
           .handle((i, o) -> i.receive().asString())
  )
        .verifyErrorMessage("Invalid subprotocol. Actual: null. Expected one of: SUBPROTOCOL,OTHER");
}

代码示例来源:origin: reactor/reactor-netty

@Test
public void testIssue460() {
  DisposableServer server =
      HttpServer.create()
           .port(0)
           .host("::1")
           .wiretap(true)
           .handle((req, res) -> res.sendWebsocket((in, out) -> Mono.never()))
           .bindNow();
  HttpClient httpClient =
      HttpClient.create()
           .addressSupplier(server::address)
           .wiretap(true)
           .headers(h -> h.add(HttpHeaderNames.HOST, "[::1"));
  StepVerifier.create(httpClient.websocket()
                 .connect())
                 .expectError()
                 .verify(Duration.ofSeconds(30));
  server.disposeNow();
}

代码示例来源:origin: reactor/reactor-netty

@Test
public void trueEnabledIncludeContentEncoding() {
  HttpServer server = HttpServer.create()
                 .port(0)
                 .compress(true);
  DisposableServer runningServer =
      server.handle((in, out) -> out.sendString(Mono.just("reply")))
         .wiretap(true)
         .bindNow(Duration.ofSeconds(10));
  HttpClient client = HttpClient.create()
                 .addressSupplier(() -> address(runningServer))
                 .wiretap(true)
                 .compress(true);
  ByteBuf res =
      client.headers(h -> Assert.assertTrue(h.contains("Accept-Encoding", "gzip", true)))
         .get()
         .uri("/test")
         .responseContent()
         .blockLast();
  runningServer.dispose();
  runningServer.onDispose()
        .block();
}

相关文章