【问题标题】:Netty Set Content-Length AutomaticallyNetty 自动设置 Content-Length
【发布时间】:2019-09-05 09:25:31
【问题描述】:

我希望 Netty(具体来说是 Reactor Netty)在我的请求中设置 Content-Length 标头。目前,即使我在请求中发送请求正文,Content-Length 标头也未设置。是否可以将Netty 配置为自动设置(如果没有请求正文,请将其设置为0)? Postman 这样做。

谢谢!

【问题讨论】:

    标签: java http netty reactor-netty


    【解决方案1】:

    我可以为 netty 回答这个问题.... @它接收。

    【讨论】:

    • 嘿@Norman 感谢您的回复。我正在尝试。将对此进行更新。
    • 您能否指出一些有关如何将处理程序添加到我的请求管道的资源?谢谢,这里对 Netty 非常陌生。
    • 在 netty 中只需调用pipeline.addLast(...)。不确定它如何与 reactor-natty 一起使用。
    【解决方案2】:

    这取决于您要发送的内容。如果是Mono 类型,那么我们将计算内容长度并发送FullHttpMessage。如果它是Flux 类型,我们会将其视为分块内容,因此我们不会计算内容长度。 这是Mono 的示例:

    public static void main(String[] args) {
        String response =
            HttpClient.create()
                    .wiretap(true)
                    .post()
                    .uri("https://postman-echo.com/post")
                    .send(Mono.just(Unpooled.wrappedBuffer("something".getBytes(Charset.defaultCharset()))))
                    .responseContent()
                    .aggregate()
                    .asString()
                    .block();
        System.out.println(response);
    }
    

    在日志中你应该可以看到:

    17:01:46.813 [reactor-http-nio-4] DEBUG reactor.netty.http.client.HttpClient - [id: 0x668bd78f, L:/xxx:xxx - R:postman-echo.com/34.239.20.132:443] WRITE: 118B
             +-------------------------------------------------+
             |  0  1  2  3  4  5  6  7  8  9  a  b  c  d  e  f |
    +--------+-------------------------------------------------+----------------+
    |00000000| 50 4f 53 54 20 2f 70 6f 73 74 20 48 54 54 50 2f |POST /post HTTP/|
    |00000010| 31 2e 31 0d 0a 75 73 65 72 2d 61 67 65 6e 74 3a |1.1..user-agent:|
    |00000020| 20 52 65 61 63 74 6f 72 4e 65 74 74 79 2f 64 65 | ReactorNetty/de|
    |00000030| 76 0d 0a 68 6f 73 74 3a 20 70 6f 73 74 6d 61 6e |v..host: postman|
    |00000040| 2d 65 63 68 6f 2e 63 6f 6d 0d 0a 61 63 63 65 70 |-echo.com..accep|
    |00000050| 74 3a 20 2a 2f 2a 0d 0a 63 6f 6e 74 65 6e 74 2d |t: */*..content-|
    |00000060| 6c 65 6e 67 74 68 3a 20 39 0d 0a 0d 0a 73 6f 6d |length: 9....som|
    |00000070| 65 74 68 69 6e 67                               |ething          |
    +--------+-------------------------------------------------+----------------+
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-04-25
      • 1970-01-01
      • 2013-12-18
      • 1970-01-01
      相关资源
      最近更新 更多