Java 通过 JSON 中的 RestTemplate POST 请求
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/4075991/
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
POST request via RestTemplate in JSON
提问by Johnny B
I didn't find any example how to solve my problem, so I want to ask you for help. I can't simply send POST request using RestTemplate object in JSON
我没有找到任何如何解决我的问题的例子,所以我想向你寻求帮助。我不能简单地使用 JSON 中的 RestTemplate 对象发送 POST 请求
Every time I get:
每次我得到:
org.springframework.web.client.HttpClientErrorException: 415 Unsupported Media Type
org.springframework.web.client.HttpClientErrorException: 415 不支持的媒体类型
I use RestTemplate in this way:
我以这种方式使用 RestTemplate:
...
restTemplate = new RestTemplate();
List<HttpMessageConverter<?>> list = new ArrayList<HttpMessageConverter<?>>();
list.add(new MappingHymansonHttpMessageConverter());
restTemplate.setMessageConverters(list);
...
Payment payment= new Payment("Aa4bhs");
Payment res = restTemplate.postForObject("http://localhost:8080/aurest/rest/payment", payment, Payment.class);
What is my fault?
我的错是什么?
回答by skaffman
The "415 Unsupported Media Type" error is telling you that the server will not accept your POST request. Your request is absolutely fine, it's the server that's mis-configured.
“415 Unsupported Media Type”错误告诉您服务器不会接受您的 POST 请求。您的请求绝对没问题,是服务器配置错误。
MappingHymansonHttpMessageConverter
will automatically set the request content-type header to application/json
, and my guess is that your server is rejecting that. You haven't told us anything about your server setup, though, so I can't really advise you on that.
MappingHymansonHttpMessageConverter
将自动将请求内容类型标头设置为application/json
,我的猜测是您的服务器正在拒绝它。但是,您没有告诉我们有关您的服务器设置的任何信息,因此我无法就此提供建议。
回答by Raghuram
回答by Mike G
If you are using Spring 3.0, an easy way to avoid the org.springframework.web.client.HttpClientErrorException: 415 Unsupported Media Typeexception, is to include the Hymanson jar files in your classpath, and use mvc:annotation-driven
config element. As specified here.
如果您使用的是 Spring 3.0,避免org.springframework.web.client.HttpClientErrorException: 415 Unsupported Media Type异常的一种简单方法是在类路径中包含 Hymanson jar 文件,并使用mvc:annotation-driven
config 元素。如此处指定。
I was pulling my hair out trying to figure out why the mvc-ajaxapp worked without any special config for the MappingHymansonHttpMessageConverter
. If you read the article I linked above closely:
我正在努力弄清楚为什么mvc-ajax应用程序在没有任何特殊配置的情况下工作MappingHymansonHttpMessageConverter
。如果您阅读我上面链接的文章:
Underneath the covers, Spring MVC delegates to a HttpMessageConverter to perform the serialization. In this case, Spring MVC invokes a MappingHymansonHttpMessageConverter built on the Hymanson JSON processor. This implementation is enabled automatically when you use the mvc:annotation-driven configuration element with Hymanson present in your classpath.
在幕后,Spring MVC 委托一个 HttpMessageConverter 来执行序列化。在这种情况下,Spring MVC 调用构建在 Hymanson JSON 处理器上的 MappingHymansonHttpMessageConverter。当您使用 mvc:annotation-driven 配置元素和 classpath 中存在的 Hymanson 时,会自动启用此实现。
回答by kanu dialani
This technique worked for me:
这种技术对我有用:
HttpHeaders headers = new HttpHeaders();
headers.setContentType(MediaType.APPLICATION_JSON);
HttpEntity<String> entity = new HttpEntity<String>(requestJson, headers);
ResponseEntity<String> response = restTemplate.put(url, entity);
I hope this helps
我希望这有帮助
回答by Mikael Lepist?
I've been using rest template with JSONObjects as follow:
我一直在使用带有 JSONObjects 的 rest 模板,如下所示:
// create request body
JSONObject request = new JSONObject();
request.put("username", name);
request.put("password", password);
// set headers
HttpHeaders headers = new HttpHeaders();
headers.setContentType(MediaType.APPLICATION_JSON);
HttpEntity<String> entity = new HttpEntity<String>(request.toString(), headers);
// send request and parse result
ResponseEntity<String> loginResponse = restTemplate
.exchange(urlString, HttpMethod.POST, entity, String.class);
if (loginResponse.getStatusCode() == HttpStatus.OK) {
JSONObject userJson = new JSONObject(loginResponse.getBody());
} else if (loginResponse.getStatusCode() == HttpStatus.UNAUTHORIZED) {
// nono... bad credentials
}
回答by Mateusz Jablonski
For me error occurred with this setup:
对我来说,此设置发生错误:
AndroidAnnotations
Spring Android RestTemplate Module
and ...
AndroidAnnotations
Spring Android RestTemplate Module
和 ...
GsonHttpMessageConverter
GsonHttpMessageConverter
Android annotations has some problems with this converted to generate POST
request without parameter. Simply parameter new Object()
solved it for me.
Android 注释在转换为生成POST
没有参数的请求方面存在一些问题。简单的参数new Object()
为我解决了它。
回答by Morgan Kenyon
I ran across this problem when attempting to debug a REST endpoint. Here is a basic example using Spring's RestTemplate class to make a POST request that I used. It took me quite a bit of a long time to piece together code from different places to get a working version.
我在尝试调试 REST 端点时遇到了这个问题。这是一个使用 Spring 的 RestTemplate 类发出我使用的 POST 请求的基本示例。我花了相当长的时间将来自不同地方的代码拼凑起来以获得一个工作版本。
RestTemplate restTemplate = new RestTemplate();
String url = "endpoint url";
String requestJson = "{\"queriedQuestion\":\"Is there pain in your hand?\"}";
HttpHeaders headers = new HttpHeaders();
headers.setContentType(MediaType.APPLICATION_JSON);
HttpEntity<String> entity = new HttpEntity<String>(requestJson,headers);
String answer = restTemplate.postForObject(url, entity, String.class);
System.out.println(answer);
The particular JSON parser my rest endpoint was using needed double quotes around field names so that's why I've escaped the double quotes in my requestJson String.
我的其余端点的特定 JSON 解析器在字段名称周围使用了所需的双引号,因此这就是我在 requestJson 字符串中转义双引号的原因。
回答by Alex Worden
I was getting this problem and I'm using Spring's RestTemplate on the client and Spring Web on the server. Both APIs have very poor error reporting, making them extremely difficult to develop with.
我遇到了这个问题,我在客户端使用 Spring 的 RestTemplate,在服务器上使用 Spring Web。这两个 API 的错误报告都非常糟糕,因此开发起来极其困难。
After many hours of trying all sorts of experiments I figured out that the issue was being caused by passing in a null reference for the POST body instead of the expected List. I presume that RestTemplate cannot determine the content-type from a null object, but doesn't complain about it. After adding the correct headers, I started getting a different server-side exception in Spring before entering my service method.
经过数小时的尝试各种实验后,我发现问题是由传递 POST 正文的空引用而不是预期的列表引起的。我认为 RestTemplate 无法从空对象确定内容类型,但不会抱怨它。添加正确的标头后,在进入我的服务方法之前,我开始在 Spring 中收到不同的服务器端异常。
The fix was to pass in an empty List from the client instead of null. No headers are required since the default content-type is used for non-null objects.
修复方法是从客户端传入一个空列表而不是 null。由于默认内容类型用于非空对象,因此不需要标头。
回答by Ganesh
This code is working for me;
这段代码对我有用;
RestTemplate restTemplate = new RestTemplate();
Payment payment = new Payment("Aa4bhs");
MultiValueMap<String, Object> map = new LinkedMultiValueMap<String, Object>();
map.add("payment", payment);
HttpEntity<MultiValueMap<String, Object>> httpEntity = new HttpEntity<MultiValueMap<String, Object>>(map, headerObject);
Payment res = restTemplate.postForObject(url, httpEntity, Payment.class);
回答by Yakhoob
I'm doing in this way and it works .
我正在这样做并且它有效。
HttpHeaders headers = createHttpHeaders(map);
public HttpHeaders createHttpHeaders(Map<String, String> map)
{
HttpHeaders headers = new HttpHeaders();
headers.setContentType(MediaType.APPLICATION_JSON);
for (Entry<String, String> entry : map.entrySet()) {
headers.add(entry.getKey(),entry.getValue());
}
return headers;
}
// Pass headers here
// 在这里传递标题
String requestJson = "{ // Construct your JSON here }";
logger.info("Request JSON ="+requestJson);
HttpEntity<String> entity = new HttpEntity<String>(requestJson, headers);
ResponseEntity<String> response = restTemplate.exchange(url, HttpMethod.POST, entity, String.class);
logger.info("Result - status ("+ response.getStatusCode() + ") has body: " + response.hasBody());
logger.info("Response ="+response.getBody());
Hope this helps
希望这可以帮助