我有两个Spring Boot应用程序。一个是进行呼叫的休息客户端。另一个只有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客户却不能?
我也尝试过在其余客户端中对特殊字符进行编码,也可以不进行编码,但是没有运气。我似乎看不到我所缺少的东西
答案 0 :(得分:0)
尝试以下更改
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();
}
}
}
答案 1 :(得分:0)
可能有2个问题:
答案 2 :(得分:0)
我也有这个问题。当我在交换方法中使用 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);