繁体   English   中英

使用 ClientBuilder 发送 JSON 正文,但使用 ContentType=application/x-www-form-urlencoded

[英]Send JSON body but with ContentType=application/x-www-form-urlencoded with ClientBuilder

我知道这个问题很奇怪。 不幸的是,我有一项服务要求所有内容都具有标题ContentType=application/x-www-form-urlencoded ,即使主体是 JSON

我正在尝试使用 JAX-RS 2.0 ClientBuilder 来调用它:

String baseUrl = "http://api.example.com/";

JSONObject body = new JSONObject();
body.put("key", "value");

Client client = ClientBuilder.newClient();
client.register(new LoggingFilter());
Builder builder = client.target(baseUrl).path("something").request();

Invocation inv = builder
    .header("Content-type", MediaType.APPLICATION_FORM_URLENCODED)
    .buildPost(Entity.json(body));
Response response = inv.invoke();

int status = response.getStatus();
// I get 415, unsupported media type (in this case is unexpected)

我检查了我的日志,尽管我正在设置application/x-www-form-urlencoded (通过MediaType )请求似乎具有application/jsonContent-type

如何强制请求具有我想要的Content-type


顺便说一句:这是我的自定义记录器:

com.acme.LoggingFilter                   I body
com.acme.LoggingFilter                   I {"key":"value"}
com.acme.LoggingFilter                   I headers
com.acme.LoggingFilter                   I {Content-type=[application/json]}

这些是我得到的日志:

 com.acme.LoggingFilter I body com.acme.LoggingFilter I {"key":"value"} com.acme.LoggingFilter I headers com.acme.LoggingFilter I {Content-type=[application/json]}

尝试使用静态Entity帮助程序方法之一的问题在于它会覆盖您可能设置的任何先前的Content-Type标头。 在您当前的情况下, Entity.json自动将标头设置为application/json

而不是使用的.json方法,你可以使用通用Entity.entity(Object, MediaType)方法。 不过,在您当前的情况下,您可以只执行Entity.entity(body, MediaType.APPLICATION_FORM_URLENCODED_TYPE) 原因是客户端将寻找知道如何将JSONObject序列化为application/x-www-form-urlencoded数据的提供者,但没有。 所以你需要先将它序列化为一个字符串。 这样处理application/x-www-form-urlencoded者不需要序列化任何东西。 所以就做

Entity.entity(body.toString(), MediaType.APPLICATION_FORM_URLENCODED_TYPE);

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM