5

我想使用 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"
4

1 回答 1

16

尝试model从代码中删除,正如我在您的 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);
}
于 2015-12-02T15:46:15.460 回答