Spring
上的后端代码。
@PostMapping("/results")
public void postResults(@RequestBody List<Result> list)
{
System.out.println(list.toString());
}
Android
代码:
void post(List<Result> list)
{
Gson gson = new Gson();
String json = gson.toJson(list);
RestTemplate restTemplate = new RestTemplate();
restTemplate.getMessageConverters().add(new MappingJackson2HttpMessageConverter());
//Failure point
restTemplate.postForEntity(URL, json, null);
}
这失败,并带有异常:
org.springframework.web.client.HttpClientErrorException:415 at org.springframework.web.client.DefaultResponseErrorHandler.handleError(DefaultResponseErrorHandler.java:88)
答案 0 :(得分:0)
如错误日志中所述,错误代码415 表示不受支持的媒体类型。因此,您应该添加标题以指示您的媒体类型。
void post(List<Result> list)
{
Gson gson = new Gson();
String json = gson.toJson(list);
RestTemplate restTemplate = new RestTemplate();
restTemplate.getMessageConverters().add(new MappingJackson2HttpMessageConverter());
HttpHeaders headers = new HttpHeaders();
headers.setContentType(MediaType.APPLICATION_JSON);
HttpEntity<String> entity = new HttpEntity<String>(json, headers);
ResponseEntity<String> response = restTemplate.put(url, entity);
}