我正在尝试使用 RestTemplate 的 POST 方法。我需要我的请求只有 1 个查询参数,没有正文(例如 localhost:8080/predictions/init?date=xxxx
)。
我目前的代码如下:
String url = "http://localhost:8080/predictions/init";
String dateToGenerate = "xxxx";
MultiValueMap<String, String> headers = new LinkedMultiValueMap<String, String>();
Map map = new HashMap<String, String>();
map.put("Content-Type", "application/json");
headers.setAll(map);
Map req_payload = new HashMap();
req_payload.put("date", dateToGenerate);
HttpEntity<?> request = new HttpEntity<>(req_payload, headers);
restTemplateApi.postForEntity(url, request, String.class);
我试图调用的 REST 控制器的一侧如下:
@PostMapping
@ResponseStatus(HttpStatus.OK)
public PredictionGenerated initializeOnePrediction(@RequestParam @NotEmpty String date) {
.............................
.............................
}
我目前收到 org.springframework.web.client.HttpClientErrorException: 400 null
。
有什么想法吗?
答案 0 :(得分:0)
如果您有多个查询参数,则在多值映射中设置所有参数,如下所示。
MultiValueMap<String, String> param= new
LinkedMultiValueMap<String, String>();
param.put("date", datevalue);
然后创建Http头添加需要的内容。
HttpHeaders headers = new HttpHeaders()
header.setContentType("application/json");
创建如下 URL。
URI url = UriComponentsBuilder.fromHttpUrl(base url)
.queryParams(param)
.build();
HttpEntity<?> request = new HttpEntity<>(req_payload,
headers);
restTemplateApi.postForEntity(url, request, String.class);