代码之家  ›  专栏  ›  技术社区  ›  dEs12ZER

如何发送POST请求以使用ARC扩展或ANGULAR5测试api Rest?

  •  0
  • dEs12ZER  · 技术社区  · 7 年前

    我试图在spring boot中测试api rest,所以我使用ARC扩展发送POST请求,但我猜我做错了。

    身份验证之后,我获得了用于测试api rest的令牌。

    下面是spring boot中的方法:

     @RequestMapping(value="/saveProjectToClient",method=RequestMethod.POST)
        public boolean saveProjectToClient(@RequestBody DTO dto){
            System.out.println("Person id  : "+dto.getIdPerson());
            System.out.println("Project id : "+dto.getIdProject());
    
             return true;
        }
    

    这个方法除了显示id之外什么都不做,我会在它工作后更改它。。

    对于圆弧延伸: enter image description here

    要在正文中发送参数,请执行以下操作:

    enter image description here

    如您所见,我得到一个错误:

       {
    "timestamp": 1526330389396,
    "status": 400,
    "error": "Bad Request",
    "exception": "org.springframework.http.converter.HttpMessageNotReadableException",
    "message": "JSON parse error: Can not deserialize instance of long out of START_OBJECT token; nested exception is com.fasterxml.jackson.databind.JsonMappingException: Can not deserialize instance of long out of START_OBJECT token at [Source: java.io.PushbackInputStream@1134a39; line: 1, column: 1]",
    "path": "/saveProjectToClient"
    }
    

    有什么问题吗?我使用post请求的方式不正确?或者spring boot中的方法编写得不好?

    编辑

    使用HttpClient的Angular5服务:

    addProjToClient(idPerson:number,idProject:number){
        if(this.authService.getToken()==null) {
          this.authService.loadToken();
        }
    
        return this.http.post(this.host+"/saveProjectToClient", {
      idPerson,
      idProject,
    }, {headers:new HttpHeaders({'Authorization':this.authService.getToken()})})
    
      }
    

    问题 :现在,当我尝试通过angular5服务调用此方法时,我没有得到任何结果,甚至没有错误,spring boot中的方法是无法访问的。

    1 回复  |  直到 7 年前
        1
  •  1
  •   Federico Luzzi    7 年前

    异常消息中明确说明了问题:

    Can not deserialize instance of long out of START_OBJECT

    Jackson无法在找到开始时反序列化long { JSON请求正文中的字符。将id封装在如下模型中就足够了:

    public class MyModel {
    
        private Long id; // use primitive type if, as I would think, id cannot be null
    
        public void setId( Long id ) {
            this.id = id;
        }
    
        public Long getId() {
            return id;
        }
    
    }
    

    然后,您显然必须告诉Spring使用自定义模型作为 @RequestBody :

    @RequestMapping( value = "/saveProjectToClient", method = RequestMethod.POST )
    public boolean saveProjectToClient( @RequestBody MyModel model ) {
        System.out.println( "ID: " + String.valueOf( model.getId() );
        return true;
    }