org.springframework.web.HttpMediaTypeNotSupportedException: Content type 'application/x-www-form-url

org.springframework.web.HttpMediaTypeNotSupportedException: Content type 'application/x-www-form-urlencoded;charset=UTF-8' not supported

异常原因:后端接口API需要的参数格式为json,但我们前端提交的数据格式为form表单。


此异常 是我在做支付宝支付的时候遇到的,有两种办法可以解决,如下所示:

修改方法一:把接口API的参数接收格式修改为接收form表单。

把红色注解@RequestBody 去掉,因为此注解表示j接收的参数格式为json

@Api(description = "支付宝相关接口")
@RestController
@RequestMapping("/alipay")
public class AlipayController {

@Resource
private AlipayService alipayService;

@ApiOperation(value = "支付宝支付")
@PostMapping(value = "pay", produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
public void pay(
@Validated @RequestBody TripOrderPay order,
HttpServletRequest request, HttpServletResponse response)
throws AlipayApiException, IOException {

String result = alipayService.alipayTradePagePay(order.getOut_trade_no(), order.getTotal_amount(), order.getSubject(), order.getBody());
response.setContentType("text/html; charset=utf-8");
response.getWriter().print(result);

}

}


修改方法二:传递的参数格式转换为 json 格式,http请求头设置为 content-type : application/json;charset=UTF-8

$.ajax({
    type: "POST",
    contentType: "application/json;charset=UTF-8",
    url: "/alipay/pay",
    data: JSON.stringify(data.field),
    dataType: 'json',
    success: function(result) {
        if(result.code == 0) {
            layer.msg('支付成功!');
        } else {
            layer.msg(result.msg);
        }
    }
});





你可能感兴趣的:(异常)