带有内容类型application / x-www-form-urlencoded的Http Post请求在Spring中不起作用

我是spring的新手,我正在尝试做HTTP POST请求应用程序/ x-www-form-url编码 ,但当我把它保存在我的标题中然后spring不认识它并且说x-www-form-urlencoded 415 Unsupported Media Type

org.springframework.web.HttpMediaTypeNotSupportedException:不支持内容类型’application / x-www-form-urlencoded’

任何人都知道如何解决它吗? 请评论我。

我的控制器的一个例子是:

 @RequestMapping(value = "/patientdetails", method = RequestMethod.POST, headers="Accept=application/x-www-form-urlencoded") public @ResponseBody List getPatientDetails( @RequestBody PatientProfileDto name) { List list = new ArrayList(); list = service.getPatient(name); return list; } 

问题是,当我们使用application / x-www-form-urlencoded时 ,Spring并不将其理解为RequestBody。 因此,如果我们想要使用它,我们必须删除@RequestBody注释。

然后尝试以下方法:

 @RequestMapping(value = "/patientdetails", method = RequestMethod.POST,consumes = MediaType.APPLICATION_FORM_URLENCODED_VALUE) public @ResponseBody List getPatientDetails( PatientProfileDto name) { List list = new ArrayList(); list = service.getPatient(name); return list; } 

请注意,删除了注释@RequestBody

您必须告诉Spring您的服务支持哪些输入内容类型。 您可以使用与您的请求的“Content-Type”标题对应的“消耗”注释元素来执行此操作。

 @RequestMapping(value = "/", method = RequestMethod.POST, consumes = {"application/x-www-form-urlencoded"}) 

如果您发布了代码,将会很有帮助。

最简单的方法是将ajax请求的内容类型设置为“application / json; charset = utf-8”,然后让你的api方法使用json。 喜欢这个

 var basicInfo = JSON.stringify( { firstName : playerProfile.firstName(), lastName : playerProfile.lastName(), gender : playerProfile.gender(), address : playerProfile.address(), country : playerProfile.country(), bio : playerProfile.bio() }); $.ajax({ url: "http://localhost:8080/social/profile/update", type: 'POST', dataType: 'json', contentType: "application/json; charset=utf-8", data: basicInfo, success: function(data) { } }); @RequestMapping(value = "/profile/update", method = RequestMethod.POST, produces = MediaType.APPLICATION_JSON_VALUE, consumes = MediaType.APPLICATION_JSON_VALUE) public ResponseEntity UpdateUserProfile(@RequestBody User usersNewDetails, HttpServletRequest request, HttpServletResponse response){ 

我猜测问题是spring boot有问题提交表单数据,这不是json通过ajax请求。 注意:ajax的默认内容类型是“application / x-www-form-urlencoded”