无法发布到后端

时间:2018-10-12 21:42:11

标签: java android spring

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)

1 个答案:

答案 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);
}