其他分享
首页 > 其他分享> > 在Spring Rest中使用JSON的HTTP POST

在Spring Rest中使用JSON的HTTP POST

作者:互联网

我想使用Spring RestTemplate进行简单的HTTP POST.
Wesb服务接受参数中的JSON,例如:{“name”:“mame”,“email”:“email@gmail.com”}

   public static void main(String[] args) {

    final String uri = "url";
    RestTemplate restTemplate = new RestTemplate();
    // Add the Jackson message converter
    restTemplate.getMessageConverters().add(new MappingJackson2HttpMessageConverter());
    // create request body
    String input = "{   \"name\": \"name\",   \"email\": \"email@gmail.com\" }";
    JsonObject request = new JsonObject();
    request.addProperty("model", input);

    // set headers
    HttpHeaders headers = new HttpHeaders();
    headers.setContentType(MediaType.APPLICATION_JSON);
    headers.set("Authorization", "Basic " + "xxxxxxxxxxxx");
    HttpEntity<String> entity = new HttpEntity<String>(request.toString(), headers);

    // send request and parse result
    ResponseEntity<String> response = restTemplate
            .exchange(uri, HttpMethod.POST, entity, String.class);

    System.out.println(response);
}

当我测试此代码时,我收到此错误:

 Exception in thread "main" org.springframework.web.client.HttpClientErrorException: 400 Bad Request

当我用Curl调用webservice时,我得到了正确的结果:

 curl -X POST -H "Authorization: Basic xxxxxxxxxx" --header "Content-Type: application/json" --header "Accept: application/json" -d "{   \"name\": \"name\",   \"email\": \"email@gmail.com\" } " "url"

解决方法:

尝试从代码中删除模型,因为我可以在你的curl请求中看到你没有使用模型属性,一切正常.试试这个:

 public static void main(String[] args) {

    final String uri = "url";
    RestTemplate restTemplate = new RestTemplate();
    // Add the Jackson message converter
    restTemplate.getMessageConverters().add(new MappingJackson2HttpMessageConverter());
    // create request body
    String input = "{\"name\":\"name\",\"email\":\"email@gmail.com\"}";


    // set headers
    HttpHeaders headers = new HttpHeaders();
    headers.setContentType(MediaType.APPLICATION_JSON);
    headers.set("Authorization", "Basic " + "xxxxxxxxxxxx");
    HttpEntity<String> entity = new HttpEntity<String>(input, headers);

    // send request and parse result
    ResponseEntity<String> response = restTemplate
            .exchange(uri, HttpMethod.POST, entity, String.class);

    System.out.println(response);
}

标签:rest,spring-mvc,spring,web-services,spring-rest
来源: https://codeday.me/bug/20190716/1475719.html