![](/img/trans.png)
[英]How to send body in restTemplate as 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/json
的Content-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.