以MIME为application-json方式提交参数示例

以 application/json作为请求头格式可以提交json字符串作为request参数。。服务端直接读取request的输入流即可拿到该完整字符串再使用jsonlib库转化为JSON对象,示例代码如下:

  • 浏览器端:

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    var obj= {
    method:"login",
    staff_id:"staff",
    password:"123"
    };

    $.ajax({
    url: "index.do",
    type:"post",
    contentType:"application/json",
    data:JSON.stringify(obj),
    success: function( data ) {
    alert("aaa");
    }
    });
  • 服务端:

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    34
    35
    36
    BufferedReader br = new BufferedReader(new InputStreamReader(
    req.getInputStream(), "UTF-8"));
    String temp;
    while ((temp = br.readLine()) != null) {
    sb.append(temp);
    }
    br.close();
    result = new String(sb.toString());
    result = URLDecoder.decode(result, "UTF-8");

    JSONObject jsonObject = new JSONObject();
    try {
    jsonObject = JSONObject.fromObject(result);
    } catch (Exception e) {
    String errorInfo = "{\"loginFlag\":\"9999\",\"loginInfo\":\"入参格式有误\"}";
    out.print(errorInfo);
    out.flush();
    out.close();
    return null;
    }

    String method = jsonObject.getString("method");

    if (method!=null&&!"".equals(method)){
    if(method.equals("login")) {
    this.login(jsonObject, resp);
    }else if(method.equals("anotherm")){
    this.anotherm(jsonObject,resp);
    }
    } else{
    String errorInfo = "{\"loginFlag\":\"9999\",\"loginInfo\":\"入参格式有误\"}";
    out.print(errorInfo);
    out.flush();
    out.close();
    return null;
    }