如何使用Spring RestTemplate表示为JSON的查询参数? [英] How to use query parameter represented as JSON with Spring RestTemplate?
问题描述
我需要使用Spring RestTemplate向具有表示为JSON的查询参数的HTTP端点发出请求。
I need to make a request to an HTTP endpoint having a query parameter represented as JSON using Spring RestTemplate.
restTemplate.getForObject(
apiRoot + "/path" + "?object={myObject}",
Response.class,
new MyObject())
这里我需要将 MyObject
转换为JSON(和URL) - 很明显)。但 RestTemplate
只需将其转换为 String
,而使用 toString
调用。 MyObject
可由Jackson转换为JSON。 UriComponentsBuilder
的行为方式相同:
Here I need MyObject
to be converted to JSON (and URL-encoded obviously). But RestTemplate
just converts it to String
with toString
call instead. MyObject
is convertable to JSON by Jackson. UriComponentsBuilder
behaves the same way:
UriComponentsBuilder.fromHttpUrl(apiRoot)
.path("/path")
.queryParam("object", new MyObject()))
.queryParam("access_token", accessToken)
.toUri()
有没有办法避免调用 ObjectMapper。 writeValueAsString
用手?
Is there a way to avoid calling ObjectMapper.writeValueAsString
by hands?
更新:澄清一下,结果我需要?object = {key :42}
在我的URI中(或以URL编码形式?object =%7B%22key%22%3A42%7D
)给出 MyObject
有一个属性 key
,其值等于 42
。
Update: to clarify, in the result I need to have ?object={"key":42}
in my URI (or in URL-encodeded form ?object=%7B%22key%22%3A42%7D
) given MyObject
has one property key
with value equal to 42
.
推荐答案
使用 writeValueAsString
有什么问题?你可以解释吗?
What is wrong with using writeValueAsString
? Can You explain?
我想到的唯一解决方案就是(我不认为杰克逊是否有办法知道这个对象应该在那一刻被序列化) :
The only solution that comes to my mind looks like (I don't think if there is a way for Jackson to know that this object should be serialized in that moment):
@Autowired
ObjectMapper objectMapper;
@Override
public void run(String... strings) throws Exception {
String urlBase = "http://localhost:8080/path";
RestTemplate restTemplate = new RestTemplate();
String url;
MultiValueMap<String, String> params = new LinkedMultiValueMap<String, String>();
params.set("object", objectMapper.writeValueAsString(new MyObject()));
UriComponentsBuilder builder = UriComponentsBuilder.fromHttpUrl(urlBase).queryParams(params);
url = builder.build().toUri().toString();
LOGGER.info("Composed before decode: " + url);
//restTemplate.getForObject(url, Void.class);
url = URLDecoder.decode(url, "UTF-8");
LOGGER.info("Composed after decode: " + url);
}
输出:
2016-04-05 16:06:46.811 INFO 6728 --- [main] com.patrykwoj.StackOverfloApplication : Composed before decode: http://localhost:8080/path?object=%7B%22key%22:43%7D
2016-04-05 16:06:46.941 INFO 6728 --- [main] com.patrykwoj.StackOverfloApplication : Composed after decode: http://localhost:8080/path?object={"key":43}
编辑:
我忘了提一下,将JSON对象作为请求参数发送通常不是一个好主意。例如,您可能会遇到JSON中的大括号问题。
I forgot to mention, that sending JSON object as request parameter is generally not a good idea. For example, You will probably face problem with curly brackets inside JSON.
这篇关于如何使用Spring RestTemplate表示为JSON的查询参数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!