Java 使用 Jersey 2 客户端发布空体

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/20585348/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-13 02:56:52  来源:igfitidea点击:

Post empty body with Jersey 2 client

javajerseyjersey-client

提问by Stine

How do I submit a post request with an empty body with a Jersey 2 client?

如何向 Jersey 2 客户端提交带有空正文的发布请求?

final MyClass result = ClientBuilder.newClient()
    .target("http://localhost:8080")
    .path("path")
    .queryParam("key", "value")
    .request(APPLICATION_JSON)
    .post(What to fill in here if the body should be left empty??, MyClass.class);


Update:this works:

更新:这有效:

final MyClass result = ClientBuilder
    .newBuilder().register(HymansonFeature).build()
    .target("http://localhost:8080")
    .path("path")
    .queryParam("key", "value")
    .request(APPLICATION_JSON)
    .post(null, MyClass.class);

采纳答案by Alden

I can't find this in the doc's anywhere, but I believe you can use nullto get an empty body:

我在文档的任何地方都找不到这个,但我相信你可以null用来得到一个空的身体:

final MyClass result = ClientBuilder.newClient()
    .target("http://localhost:8080")
    .path("path")
    .queryParam("key", "value")
    .request(APPLICATION_JSON)
    .post(Entity.json(null), MyClass.class)

回答by roanbaga

I don't know if the version change it. But, the following doesn't work:

不知道版本有没有变化。但是,以下不起作用:

builder.put( Entity.json( null ) );

builder.put( Entity.json( null ) );

Where, the following works fine:

在哪里,以下工作正常:

builder.put( Entity.json( "" ) );

builder.put( Entity.json( "" ) );

回答by Gapmeister66

I found that this worked for me:

我发现这对我有用:

Response r = client
    .target(url)
    .path(path)
    .queryParam(name, value)
    .request()
    .put(Entity.json(""));

Pass an empty string, not a null value.

传递空字符串,而不是空值。

回答by Emmanuel Osimosu

Just post an empty txt.

只需发布一个空的txt。

   .post(Entity.text(""));

回答by Michael

It worked for me only with an empty json object string

它仅适用于空的 json 对象字符串

.post(Entity.json("{}")

All other solutions, still produced 400 Bad Request

所有其他解决方案,仍在生产 400 Bad Request

P.S. The request is done using MediaType.APPLICATION_JSON

PS请求是使用完成的 MediaType.APPLICATION_JSON