HTTP400 的坑

来源:互联网 发布:淘宝衣服店铺排名查询 编辑:程序博客网 时间:2024/05/20 19:31

令人纠结的400 bad request

本人之前一直是自己写ajax和controller,传值的类型和名称都是自己定义,所以基本上没有出现过400,奈何如今前后端分离….下面介绍一下本次开发与前端联调遇见的坑

传值格式

接口写好后,测试都是用Insomnia工具发请求,表单格式传值,轻松愉快200(以前都是这样传的key,value对应),奈何对接时直接400,尼玛,前端json传值!!直接跪了,让前端改传值方式,弄了半天没结果,说是没用过fetch js传其他类型数据,于是乎改后端,将所有参数封装进对象当中,并使用@RequestBody注解

  @RequestMapping(value = "/simple/testConvert", method = RquestMethod.POST)    @ResponseBody    public String testDateConvert(@RequestBody Paramters paramters) {        System.out.println(JSON.toJSONString(paramters));        return "hello word!";    }

所传字段类型不匹配

任务是分给我和另外一个同事合作的,新同事比较特立独行,直接修改了我的接口文档,将我本来定义的String类型的传值定义成了数组“A,B,C”换成了[“A”,”B”,”C”],400华丽出场。字段类型是400的常见原因,解决方法比较简单,改成需要的类型

日期date与long的转换

调试同事接口的时候,出现了个奇怪的现象http://localhost:8080/MANAGER-APP/blogger/queryBloggerList?source=1&beginTime=&endTime=总是400,然而将后面两个参数删除http://localhost:8080/MANAGER-APP/blogger/queryBloggerList?source=1正常访问,why难道不是等价的吗?原因未解,希望有知道的大神留言相告,不胜感激。最后查查资料,方法有3

  1. 将时间类型从Date改成Long
  2. 使用post+json传值
  3. 重写绑定方法
    前两个方法比较简单,mark一下最后一种,上代码

    @InitBinderprivate void dateBinder(WebDataBinder binder) {    //设置你需要的日期格式,传入的参数必须能被这种格式解析    SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");    //Create a new CustomDateEditor    CustomDateEditor editor = new CustomDateEditor(dateFormat, true);    //Register it as custom editor for the Date type,以后传入的时间都用这个格式解析    binder.registerCustomEditor(Date.class, editor);}

    加上面方法加在controller类中,已经证明好使

0 0
原创粉丝点击