RestTemplate:如何一起发送URL和查询参数

我正在尝试在URL中传递路径参数和查询参数,但出现一个奇怪的错误。下面是代码

    String url = "http://test.com/Services/rest/{id}/Identifier"

Map<String, String> params = new HashMap<String, String>();

params.put("id", "1234");

UriComponentsBuilder builder = UriComponentsBuilder.fromUriString(url)

.queryParam("name", "myName");

String uriBuilder = builder.build().encode().toUriString();

restTemplate.exchange(uriBuilder , HttpMethod.PUT, requestEntity,

class_p, params);

我的网址正在变成 http://test.com/Services/rest/%7Bid%7D/Identifier?name=myName

我应该怎么做才能使其正常工作。我期望http://test.com/Services/rest/{id}/Identifier?name=myName参数可以将id添加到网址中

请提出建议。提前致谢

回答:

我将使用buildAndExpandfrom UriComponentsBuilder来传递所有类型的URI参数。

例如:

String url = "http://test.com/solarSystem/planets/{planet}/moons/{moon}";

// URI (URL) parameters

Map<String, String> urlParams = new HashMap<>();

urlParams.put("planets", "Mars");

urlParams.put("moons", "Phobos");

// Query parameters

UriComponentsBuilder builder = UriComponentsBuilder.fromUriString(url)

// Add query parameter

.queryParam("firstName", "Mark")

.queryParam("lastName", "Watney");

System.out.println(builder.buildAndExpand(urlParams).toUri());

/**

* Console output:

* http://test.com/solarSystem/planets/Mars/moons/Phobos?firstName=Mark&lastName=Watney

*/

restTemplate.exchange(builder.buildAndExpand(urlParams).toUri() , HttpMethod.PUT,

requestEntity, class_p);

/**

* Log entry:

* org.springframework.web.client.RestTemplate Created PUT request for "http://test.com/solarSystem/planets/Mars/moons/Phobos?firstName=Mark&lastName=Watney"

*/

以上是 RestTemplate:如何一起发送URL和查询参数 的全部内容, 来源链接: utcz.com/qa/421942.html

回到顶部