RestTemplate uriVariables未展开

use*_*874 22 java spring resttemplate

我尝试使用弹簧RestTemplate.getForObject()访问休息端点,但我的uri变量未展开,并作为参数附加到url.这是我到目前为止所得到的:

Map<String, String> uriParams = new HashMap<String, String>();
uriParams.put("method", "login");
uriParams.put("input_type", DATA_TYPE);
uriParams.put("response_type", DATA_TYPE);
uriParams.put("rest_data", rest_data.toString());
String responseString = template.getForObject(endpointUrl, String.class, uriParams);
Run Code Online (Sandbox Code Playgroud)

endpointUrl变量的值是,http://127.0.0.1/service/v4_1/rest.php并且它的确是它所谓的,但我希望http://127.0.0.1/service/v4_1/rest.php?method=login&input_type...被调用.任何提示都表示赞赏.

我正在使用Spring 3.1.4.RELEASE

问候.

小智 34

在它中没有附加一些查询字符串逻辑RestTemplate基本上替换变量,如{foo}它们的值:

http://www.sample.com?foo={foo}
Run Code Online (Sandbox Code Playgroud)

变为:

http://www.sample.com?foo=2
Run Code Online (Sandbox Code Playgroud)

如果foo是2.

  • 它可以工作,但你需要在你的网址中有变量(这是变量的映射) (3认同)
  • 这里稍微大一点的答案会有所帮助;当我第一次阅读您的答案时,它并没有真正点击。花点时间展示实际的代码片段,其中将 URL 表示为字符串,然后是映射中的值,然后调用 getForObject(string, map)。我对此投了赞成票,但应该让 IMO 更加明确。 (3认同)
  • 你会认为这会在 Javadocs 中处于领先地位......但我不得不来到这里,找到一个 5 岁的答案,才能找到它。 (3认同)

Ban*_*ane 13

user180100当前标记的答案在技术上是正确的,但不是很明确。这是一个更明确的答案,以帮助那些在我身后的人,因为当我初读z的答案时,这对我来说没有意义。

String url = "http://www.sample.com?foo={fooValue}";

Map<String, String> uriVariables = new HashMap();
uriVariables.put("fooValue", 2);

// "http://www.sample.com?foo=2"
restTemplate.getForObject(url, Object.class, uriVariables);
Run Code Online (Sandbox Code Playgroud)

  • 请注意,`RestTemplate` 也有一个采用可变参数的方法签名,因此您也可以这样做:`int foo = 2; restTemplate.getForObject("http://www.sample.com?foo={foo}", Object.class, foo);` (3认同)