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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/34782025/
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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-11 15:59:12  来源:igfitidea点击:

Http Post request with content type application/x-www-form-urlencoded not working in Spring

javajqueryspringrestspring-mvc

提问by Rajesh

Am new to spring currently am trying to do HTTP POST request application/x-www-form-url encodedbut when i keep this in my headers then spring not recognizing it and saying 415 Unsupported Media Typefor x-www-form-urlencoded

是新来春目前正在试图做的HTTP POST请求的应用程序/ x-WWW的形式,URL编码,但是当我守这在我的头,然后春天不承认它,并说415 Unsupported Media Typex-www-form-urlencoded

org.springframework.web.HttpMediaTypeNotSupportedException: Content type 'application/x-www-form-urlencoded' not supported

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

Can any one know how to solve it? please comment me.

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

An example of my controller is:

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

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

回答by SpeaksBinary

You have to tell Spring what input content-type is supported by your service. You can do this with the "consumes" Annotation Element that corresponds to your request's "Content-Type" header.

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

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

It would be helpful if you posted your code.

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

回答by Douglas Ribeiro

The problem is that when we use application/x-www-form-urlencoded, Spring doesn't understand it as a RequestBody. So, if we want to use this we must remove the @RequestBodyannotation.

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

Then try the following:

然后尝试以下操作:

@RequestMapping(value = "/patientdetails", method = RequestMethod.POST,consumes = MediaType.APPLICATION_FORM_URLENCODED_VALUE)
public @ResponseBody List<PatientProfileDto> getPatientDetails(
        PatientProfileDto name) {


    List<PatientProfileDto> list = new ArrayList<PatientProfileDto>();
    list = service.getPatient(name);
    return list;
}

Note that removed the annotation @RequestBody

请注意,删除了注释@RequestBody

回答by Eshiett Oto-obong

The easiest thing to do is to set the content type of your ajax request to "application/json; charset=utf-8"and then let your API method consume JSON. Like this:

最简单的做法是将您的 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<ResponseModel> UpdateUserProfile(
    @RequestBody User usersNewDetails,
    HttpServletRequest request,
    HttpServletResponse response
) {
    // ...
}

I guess the problem is that Spring Boot has issues submitting form data which is not JSON via ajax request.

我想问题是 Spring Boot 在通过 ajax 请求提交不是 JSON 的表单数据时存在问题。

Note: the default content type for ajax is "application/x-www-form-urlencoded".

注意:ajax 的默认内容类型是"application/x-www-form-urlencoded".

回答by DHyman

you should replace @RequestBodywith @RequestParam, and do not accept parameters with a java entity.

此时应更换@RequestBody@RequestParam,并且不接受与Java实体参数。

Then you controller is probably like this:

那么你的控制器可能是这样的:

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

回答by Chris Valinhas

The solution can be found here https://github.com/spring-projects/spring-framework/issues/22734

解决方案可以在这里找到https://github.com/spring-projects/spring-framework/issues/22734

you can create two separate post request mappings. For example.

您可以创建两个单独的发布请求映射。例如。

@PostMapping(path = "/test", consumes = "application/json")
public String test(@RequestBody User user) {
  return user.toString();
}

@PostMapping(path = "/test", consumes = "application/x-www-form-urlencoded")
public String test(User user) {
  return user.toString();
}

回答by Virendra khade

replace contentType : "application/x-www-form-urlencoded", by dataType : "text" as wildfly 11 doesn't support mentioned contenttype..

替换 contentType : "application/x-www-form-urlencoded", by dataType : "text" 因为 wildfly 11 不支持提到的内容类型..

回答by harun ugur

Remove @ResponseBody annotation from your use parameters in method. Like this;

从方法中的使用参数中删除 @ResponseBody 注释。像这样;

   @Autowired
    ProjectService projectService;

    @RequestMapping(path = "/add", method = RequestMethod.POST)
    public ResponseEntity<Project> createNewProject(Project newProject){
        Project project = projectService.save(newProject);

        return new ResponseEntity<Project>(project,HttpStatus.CREATED);
    }