站内搜索

workerdance.com — Trusted craft, unfailing commitment
返回文章列表
前端

JSP页面调用接口发送JSON格式数据

本文写于 2017 年,文中涉及的软件版本可能已有变化,核心排查思路仍可参考。

问题描述:

  1. 想在JSP页面测试调用后台接口,这个接口调用后需要进行页面跳转,所有无法使用Postman等工具

  2. 接口接收的是JSON数据格式

在摸索了一番后,直接上可用代码片段:

<html>

<head>
    <title>支付测试</title>
</head>

<body>
    <script src="https://cdn.bootcss.com/jquery/3.2.1/jquery.min.js"></script>
    <script>
    function login {
        var myData = {
            "account": "danisa",
            "password": "111111",
            "userType": 1
        };
        $.ajax({
            type: "POST",
            url: "http://127.0.0.1:8088/api/1.0/web/login",
            data: JSON.stringify(myData),
            contentType: "application/json;charset=UTF-8"
        });
    }
    </script>
    <h1>登录</h1>
    <input type="button" value="click me to login" onclick="login">
</body>

</html>

其中需要注意的有两个地方:

  1. contentType,需要填成 application/json;charset=UTF-8,否则会报格式错误
org.springframework.web.HttpMediaTypeNotSupportedException: Content type 'application/x-www-form-urlencoded;charset=UTF-8' not supported
  1. data部分,要使用JSON.stringify方法格式化json对象,否则会报以下错误
Caused by: com.fasterxml.jackson.core.JsonParseException: Unrecognized token 'account': was expecting ('true', 'false' or 'null')
workerdance
workerdance

记录开发与运维中的实践和踩坑。