[英]GET Request Works in Postman but not with SpringBoot RestTemplate
我有两个 Spring Boot 应用程序。 一个是进行休息调用的休息客户端。 另一个只有 Rest 端点的应用程序。
当 Rest 客户端访问 rest 端点时,它会失败。
这是用于命中其余端点的代码:
HttpHeaders headers = new HttpHeaders();
headers.set(ACCEPT, APPLICATION_JSON);
headers.set(CONTENT_TYPE, APPLICATION_JSON);
HttpEntity entity = new HttpEntity(headers);
UriComponentsBuilder builder = UriComponentsBuilder
.fromHttpUrl(url)
.queryParam(EMAIL, URLEncoder.encode(email, "UTF-8"))
.queryParam(ADDRESS, URLEncoder.encode(address, "UTF-8"));
ResponseEntity<Address> response =
commonRestTemplate
.exchange(builder.toUriString(),
HttpMethod.GET, entity, Address.class);
这是客户端尝试访问的其余端点:
@RestController
@AllArgsConstructor
public class AddressController {
private final RestTemplate commonRestTemplate;
// constructor and other rest endpoints
@RequestMapping(value = "/", method = RequestMethod.GET)
public @ResponseBody ResponseEntity<Address> getAddress(@RequestParam String email, @RequestParam String address) {
try {
// do soemthing
} catch (RuntimeException e)
{
LOGGER.error(e.getMessage(), e);
return status(HttpStatus.INTERNAL_SERVER_ERROR).build();
}
}
}
这是我在带有其余端点的应用程序中看到的错误:
2020-03-26 16:33:53.619 WARN 9 --- [nio-8080-exec-1] .w.s.m.s.DefaultHandlerExceptionResolver : Resolved [org.springframework.web.bind.MissingServletRequestParameterException: Required String parameter 'address' is not present]
2020-03-26 16:50:02.691 ERROR 9 --- [nio-8080-exec-9] u.c.h.s.s.controller.AddressController : Key may not be empty
为什么 Rest 调用适用于 Postman 而不是我的 Rest 客户端?
我也尝试过在其他客户端中对特殊字符进行编码和不编码,但都没有运气。 我似乎看不到我错过了什么
尝试以下更改
UriComponentsBuilder builder = UriComponentsBuilder .fromHttpUrl(url)
.queryParam("email", URLEncoder.encode(email, "UTF-8"))
.queryParam("address", URLEncoder.encode(address, "UTF-8"));
@RestController
@AllArgsConstructor
public class AddressController {
private final RestTemplate commonRestTemplate;
// constructor and other rest endpoints
@RequestMapping(value = "/", method = RequestMethod.GET)
public @ResponseBody ResponseEntity<Address> getAddress(@RequestParam("email") String email, @RequestParam("address") String address) {
try {
// do soemthing
} catch (RuntimeException e)
{
LOGGER.error(e.getMessage(), e);
return status(HttpStatus.INTERNAL_SERVER_ERROR).build();
}
}
}
可以是2个问题:
我也有这个问题。 当我在交换方法中使用 uri 而不是 string 时,它解决了。
ResponseEntity<String> responseEntity = null;
Map<String, String> map = generate map to keep key and value of necessaryparameters;
UriComponentsBuilder uriComponentsBuilder = UriComponentsBuilder.fromHttpUrl("SERVICE_URL");
map.forEach((k, v) -> {
uriComponentsBuilder.queryParam(k, v);
});
URI uri = uriComponentsBuilder.build(false).encode("windows-1256").toUri();
responseEntity = new RestTemplate().exchange(uri, HttpMethod.POST, request, String.class);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.