简单的休息JSON POST,java作为服务器,jquery作为客户端
作者:互联网
在我提出问题之前,我必须说我已经阅读了20多个关于这个问题的问题和文章,但没有一个能解决它.
我的问题是我在java中有一个安静的服务器,如下所示:
@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 “errors message” : “Content type ‘application/x-www-form
urlencoded;charset=UTF-8’ not supported”, “type” :
“HttpMediaTypeNotSupportedError”
所以我尝试通过添加contentType来修复它:
$.ajax({
url:"/downloadByCode",
contentType:"application/json",
type:"POST",
data: JSON.stringify({"name":"value"}) });
400 “errors message” : “Could not instantiate JAXBContext for class
[class java.lang.String]: null; nested exception is
javax.xml.bind.JAXBException\n – with linked
exception:\n[java.lang.NullPointerException”, “type”
:”HttpMessageConversionError”
我试图直接发送json对象而不是JSON.stringify,它给出了相同的400错误.
我试图在@requestMapping中添加不同的消耗但仍然没有运气.
我试图定义自己的类而不是JsonNode,但它不会改变任何东西.
有任何想法吗?
解决方法:
请尝试创建新类:
public class InputData{
private String name;
public String getName(){
return name;
}
public void setName(String name){
this.name = name;
}
}
然后
public void downloadByCode(@RequestBody InputData stringRequest, final HttpServletResponse response)
和
$.ajax({
url:"/downloadByCode",
contentType:"application/json",
type:"POST",
data: JSON.stringify({"name":"value"}) });
标签:java,jquery,json,ajax,restful-architecture 来源: https://codeday.me/bug/20190722/1503605.html