标签:java jquery json ajax restful-architecture
在我提出问题之前,我必须说我已经阅读了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
本站声明: 1. iCode9 技术分享网(下文简称本站)提供的所有内容,仅供技术学习、探讨和分享; 2. 关于本站的所有留言、评论、转载及引用,纯属内容发起人的个人观点,与本站观点和立场无关; 3. 关于本站的所有言论和文字,纯属内容发起人的个人观点,与本站观点和立场无关; 4. 本站文章均是网友提供,不完全保证技术分享内容的完整性、准确性、时效性、风险性和版权归属;如您发现该文章侵犯了您的权益,可联系我们第一时间进行删除; 5. 本站为非盈利性的个人网站,所有内容不会用来进行牟利,也不会利用任何形式的广告来间接获益,纯粹是为了广大技术爱好者提供技术内容和技术思想的分享性交流网站。