我需要进行一个包含自定义头信息和查询参数的 REST
调用。我只设置了带有头信息(没有主体)的 HttpEntity
,并使用以下方式的 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
无法解析请求到处理程序,导致客户端失败。通过调试,发现似乎没有发送请求参数。
当我使用一个请求正文和没有查询参数的POST
进行交换时,它可以正常工作。
有人有任何想法吗?
exchange
替换成getForEntity
是一个很好的建议,可以让代码更简洁:restTemplate.getForEntity(builder.build().encode().toUri(), String.class);
。 - Fernando M. Pinheiroexchange
并提供ParameterizedTypeReference
。此示例可以更进一步地简化,将builder.build().encode().toUri()
替换为builder.toUriString()
。 - mirzmasterbuilder.toUriString()
。 - Michael Piefel.build().toUriString()
而不是简单的.toUriString()
,则可以解决此问题。这样可以跳过调用.encode()
来解决问题。请参见https://docs.spring.io/spring-framework/docs/current/javadoc-api/org/springframework/web/util/UriComponentsBuilder.html#toUriString--。 - riverhorse