弹簧 RestTemplate GET 与参数

2022-08-31 04:48:49

我必须进行包含自定义标头和查询参数的调用。我只用标题(没有正文)设置我的,我使用的方法如下:RESTHttpEntityRestTemplate.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);

这在客户端失败,无法将请求解析为处理程序。调试后,看起来请求参数未发送。dispatcher servlet

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

有人有什么想法吗?


答案 1

要轻松操作URL/路径/参数/等,您可以使用Spring的UriComponentsBuilder类创建一个URL模板,其中包含参数的放置物,然后在调用中为这些参数提供值。它比手动连接字符串更清晰,并且可以为您处理URL编码:RestOperations.exchange(...)

HttpHeaders headers = new HttpHeaders();
headers.set(HttpHeaders.ACCEPT, MediaType.APPLICATION_JSON_VALUE);
HttpEntity<?> entity = new HttpEntity<>(headers);

String urlTemplate = UriComponentsBuilder.fromHttpUrl(url)
        .queryParam("msisdn", "{msisdn}")
        .queryParam("email", "{email}")
        .queryParam("clientVersion", "{clientVersion}")
        .queryParam("clientType", "{clientType}")
        .queryParam("issuerName", "{issuerName}")
        .queryParam("applicationName", "{applicationName}")
        .encode()
        .toUriString();

Map<String, ?> params = new HashMap<>();
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<String> response = restOperations.exchange(
        urlTemplate,
        HttpMethod.GET,
        entity,
        String.class,
        params
);

答案 2

uriVariables 也会在查询字符串中展开。例如,以下调用将展开帐户和名称的值:

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

所以实际的请求网址将是

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

有关更多详细信息,请查看 HierarchicalUriComponents.expandInternal(UriTemplateVariables)。Spring的版本是3.1.3。