我必须进行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做一个交换时,它工作得很好。
有人有什么想法吗?
我也尝试过类似的东西,RoboSpice的例子帮助我解决了这个问题:
HttpHeaders headers = new HttpHeaders();
headers.set("Accept", "application/json");
HttpEntity<String> request = new HttpEntity<>(input, createHeader());
String url = "http://awesomesite.org";
Uri.Builder uriBuilder = Uri.parse(url).buildUpon();
uriBuilder.appendQueryParameter(key, value);
uriBuilder.appendQueryParameter(key, value);
...
String url = uriBuilder.build().toString();
HttpEntity<String> response = restTemplate.exchange(url, HttpMethod.GET, request , String.class);
String uri = http://my-rest-url.org/rest/account/{account};
Map<String, String> uriParam = new HashMap<>();
uriParam.put("account", "my_account");
UriComponents builder = UriComponentsBuilder.fromHttpUrl(uri)
.queryParam("pageSize","2")
.queryParam("page","0")
.queryParam("name","my_name").build();
HttpEntity<String> requestEntity = new HttpEntity<>(null, getHeaders());
ResponseEntity<String> strResponse = restTemplate.exchange(builder.toUriString(),HttpMethod.GET, requestEntity,
String.class,uriParam);
//final URL: http://my-rest-url.org/rest/account/my_account?pageSize=2&page=0&name=my_name
RestTemplate:使用UriComponents (URI变量和请求参数)构建动态URI
至少从Spring 3开始,许多RestTemplate方法不是使用UriComponentsBuilder来构建URL(这有点啰嗦),而是在参数路径中接受占位符(不仅仅是交换)。
从文档中可以看到:
Many of the RestTemplate methods accepts a URI template and URI
template variables, either as a String vararg, or as
Map<String,String>.
For example with a String vararg:
restTemplate.getForObject(
"http://example.com/hotels/{hotel}/rooms/{room}", String.class, "42", "21");
Or with a Map<String, String>:
Map<String, String> vars = new HashMap<>();
vars.put("hotel", "42");
vars.put("room", "21");
restTemplate.getForObject("http://example.com/hotels/{hotel}/rooms/{room}",
String.class, vars);
参考:https://docs.spring.io/spring/docs/current/spring-framework-reference/integration.html # rest-resttemplate-uri
如果你查看JavaDoc for RestTemplate并搜索“URI Template”,你可以看到哪些方法可以使用占位符。