在我提问之前,我必须说我已经阅读了20多个关于这个问题的问题和文章,但是没有一个能够解决它。
我的问题是,我有一个像这样的Java RESTful服务器:
@RequestMapping (value = "/downloadByCode", method = RequestMethod.POST)
@ResponseBody
public void downloadByCode(@RequestBody final String stringRequest, final HttpServletResponse response)
{
try
{
final ObjectMapper objectMapper = new ObjectMapper();
final JsonNode jsonRequest = objectMapper.readValue(stringRequest, JsonNode.class);
// ...
// some processings here to create the result
// ....
final ServletOutputStream outputStream = response.getOutputStream();
outputStream.write(result);
// Flush the result
outputStream.flush();
}
catch (final Exception exception)
{
LOG.debug("Exception Thrown [downloadByCode]", exception);
}
}
我尝试了不同的方法在jquery中向该服务器发送json(但它们都导致错误):
$.ajax({
url:"/downloadByCode",
type:"POST",
data: JSON.stringify({"name":"value"}) });
415 "错误信息":"不支持内容类型'application/x-www-form-urlencoded;charset=UTF-8'","类型":"HttpMediaTypeNotSupportedError"
因此,我尝试通过添加contentType来修复它:
$.ajax({
url:"/downloadByCode",
contentType:"application/json",
type:"POST",
data: JSON.stringify({"name":"value"}) });
400错误消息:"无法为类[class java.lang.String]实例化JAXBContext:null;嵌套异常是javax.xml.bind.JAXBException - 有关链接异常:[java.lang.NullPointerException","type":"HttpMessageConversionError"
我尝试直接发送json对象而不是JSON.stringify,但仍然出现了相同的400错误。
我尝试在@requestMapping中添加不同的consumes,但仍然没有成功。
我尝试定义自己的类而不是JsonNode,但这并没有改变任何东西。
有什么想法吗?