在 Spring Rest 中使用 JSON 的 HTTP POST
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/34045321/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
HTTP POST using JSON in Spring Rest
提问by youssef Liouene
I would like to make a simple HTTP POST using Spring RestTemplate.
the Wesb service accept JSON in parameter for example: {"name":"mame","email":"[email protected]"}
我想使用 Spring RestTemplate 做一个简单的 HTTP POST。Wesb 服务在参数中接受 JSON,例如:{"name":"mame","email":"[email protected]"}
public static void main(String[] args) {
final String uri = "url";
RestTemplate restTemplate = new RestTemplate();
// Add the Hymanson message converter
restTemplate.getMessageConverters().add(new MappingHymanson2HttpMessageConverter());
// create request body
String input = "{ \"name\": \"name\", \"email\": \"[email protected]\" }";
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);
}
When I test this code I got this error:
当我测试这段代码时,我收到了这个错误:
Exception in thread "main" org.springframework.web.client.HttpClientErrorException: 400 Bad Request
when I call webservice with Curl I have correct result:
当我用 Curl 调用 webservice 时,我得到了正确的结果:
curl -X POST -H "Authorization: Basic xxxxxxxxxx" --header "Content-Type: application/json" --header "Accept: application/json" -d "{ \"name\": \"name\", \"email\": \"[email protected]\" } " "url"
回答by Nikolay Rusev
try to remove model
from the code, as i can see in your curl request you didn't use model attribute and everything works. try this:
尝试model
从代码中删除,正如我在您的 curl 请求中看到的那样,您没有使用模型属性并且一切正常。尝试这个:
public static void main(String[] args) {
final String uri = "url";
RestTemplate restTemplate = new RestTemplate();
// Add the Hymanson message converter
restTemplate.getMessageConverters().add(new MappingHymanson2HttpMessageConverter());
// create request body
String input = "{\"name\":\"name\",\"email\":\"[email protected]\"}";
// 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);
}