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

后端 未结 7 1628
逝去的感伤
逝去的感伤 2020-11-27 06:19

Am new to spring currently am trying to do HTTP POST request application/x-www-form-url encoded but when i keep this in my headers then spring not recognizing it an

7条回答
  •  攒了一身酷
    2020-11-27 07:05

    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:

    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
    ) {
        // ...
    }
    

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

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

提交回复
热议问题