如何使用Spring RestTemplate在url中将JSON作为参数发送? [英] How to send JSON as a parameter in url using Spring RestTemplate?

查看:758
本文介绍了如何使用Spring RestTemplate在url中将JSON作为参数发送?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试实现以下目标:

I am trying to achieve same thing as this: How to use query parameter represented as JSON with Spring RestTemplate?, sending JSON string as a URL parameter in restTemplate.exchange().

被接受的答案提到将JSON对象作为请求参数发送通常不是一个好主意,因为您可能会遇到JSON内大括号的问题.当我尝试对API进行GET调用时,正是这种情况.由于这是另一个系统的API,因此我不能要求他们更改格式,而必须调用GET端点,并将JSON作为参数传递.如何在restTemplate.exchange()通话中实现此目标?

The accepted answer mentions that sending JSON object as request parameter is generally not a good idea since you will probably face problem with curly brackets inside JSON. That is exactly what is happening when I am trying to make a GET call to an API. Since this is an API from another system, I cannot ask them to change the format and will have to call the GET endpoint, passing JSON as parameter. How can I achieve this in restTemplate.exchange() call?

注意:提到的相关问题并未指导如何解决此问题,并且我没有足够的声誉对其发表评论以询问答案的人.

Note: The mentioned related question does not guide on how to overcome this problem and I do not have enough reputation to comment on it to ask the author of the answer.

推荐答案

回答我自己的问题.虽然在查询/URL参数中传递像这样的JSON是一个坏主意,但是这里有一个建议的解决方法:

Answering my own question. While it is a bad idea to pass JSON like this in a query/url parameter, there is a workaround as suggested here: https://jira.spring.io/browse/SPR-9220?focusedCommentId=76760&page=com.atlassian.jira.plugin.system.issuetabpanels:comment-tabpanel#comment-76760.
Replicating the code here in case this link goes dead:

String url = "http://localhost:8983/solr/select?wt=json&indent=true&fl=*&q=*:*&fq={!geofilt}&sfield=venue_location&pt=28.0674,-80.5595&d=25";
URI uri = UriComponentsBuilder.fromUriString(url).build().encode().toUri();

System.out.println(uri);
// http://localhost:8983/solr/select?wt=json&indent=true&fl=*&q=*:*&fq=%7B!geofilt%7D&sfield=venue_location&pt=28.0674,-80.5595&d=25

基本上,与其将具有JSON查询/URL参数的url作为字符串传递,不如将其作为URI传递.然后像以前一样调用exchange方法,但是使用URI而不是String:

Basically, instead of passing url having JSON query/url parameters as a string, pass it as a URI. Then call exchange method as before, but with URI instead of String:

restTemplate.exchange(uri, HttpMethod.GET, requestEntity, String.class)

这篇关于如何使用Spring RestTemplate在url中将JSON作为参数发送?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆