我必须打一个REST电话,其中包括自定义标头和查询参数。我只设置HttpEntity了标题(没有正文),然后使用以下RestTemplate.exchange()方法:
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);
这在客户端失败,dispatcher servlet因为无法将请求解析为处理程序。调试完成后,似乎没有发送请求参数。
dispatcher servlet
当我POST使用请求正文和无查询参数进行交换时,它工作正常。
有人有什么想法吗?
为了轻松地操纵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.toUriString(), HttpMethod.GET, entity, String.class);