如何使用参数Spring RestTemplate GET?

内容来源于 Stack Overflow,并遵循CC BY-SA 3.0许可协议进行翻译与使用

  • 回答 (2)
  • 关注 (0)
  • 查看 (210)

我必须做一个包含自定义标题和查询参数的REST调用。我只设置了标头HttpEntity(无Body),并使用RestTemplate.exchange()方法,如下所示:

HttpHeaders headers = new HttpHeaders();
headers.set("Accept", "application/json");

Map<String, String> params = new HashMap<String, String>();
params.put("msisdn", msisdn);
params.put("email", email);
params.put("clientVersion", clientVersion);
params.put("clientType", clientType);
params.put("issuerName", issuerName);
params.put("applicationName", applicationName);

HttpEntity entity = new HttpEntity(headers);

HttpEntity<String> response = restTemplate.exchange(url, HttpMethod.GET, entity, String.class, params);

这在客户端失败,调度程序servlet无法将请求解析为处理程序。Havinf调试它,它看起来像请求参数没有被发送。

当我使用请求Body并且没有查询参数与POST进行交换时,它工作得很好。

有没有人有任何想法?

提问于
用户回答回答于

还在查询字符串中展开uriVariable。例如,下面的调用将扩展帐户和名称的值:

restTemplate.exchange("http://my-rest-url.org/rest/account/{account}?name={name}",
    HttpMethod.GET,
    httpEntity,
    clazz,
    "my-account",
    "my-name"
);

因此,实际的请求url将是

http://my-rest-url.org/rest/account/my-account?name=my-name

用户回答回答于

要轻松地操作URL/path/params/等等,可以使用Spring的UriComponentsBuilder类。手动连接字符串更干净,它为你处理URL编码:

HttpHeaders headers = new HttpHeaders();
headers.set("Accept", MediaType.APPLICATION_JSON_VALUE);

UriComponentsBuilder builder = UriComponentsBuilder.fromHttpUrl(url)
        .queryParam("msisdn", msisdn)
        .queryParam("email", email)
        .queryParam("clientVersion", clientVersion)
        .queryParam("clientType", clientType)
        .queryParam("issuerName", issuerName)
        .queryParam("applicationName", applicationName);

HttpEntity<?> entity = new HttpEntity<>(headers);

HttpEntity<String> response = restTemplate.exchange(
        builder.build().encode().toUri(), 
        HttpMethod.GET, 
        entity, 
        String.class);

扫码关注云+社区