尝试从离子3项目到java webservice的http.post时出现错误415不支持的媒体类型

时间:2017-10-24 22:27:35

标签: angular http jersey

我有一个java后端项目,它使用JERSEY和一个离子3项目作为前端。我无法使post方法起作用,尽管get方法工作正常。

这是post方法>

      @POST
      @Consumes(MediaType.APPLICATION_JSON)
      @Path("/")
      public Response create(Oferta oferta) throws SQLException,                                    ClassNotFoundException{
    ofertaDAO dao = new ofertaDAO();
    dao.insert(oferta);
    return Response
        .status(200)
        .header("Access-Control-Allow-Origin", "*")
        .header("Access-Control-Allow-Headers", "origin, content-type, accept, authorization")
        .header("Access-Control-Allow-Credentials", "true")
        .header("Access-Control-Allow-Methods", "GET, POST, PUT,      DELETE, OPTIONS, HEAD")
        .header("Access-Control-Max-Age", "1209600")
        .entity(oferta)
        .build();

}

我试图以两种不同的方式在我的离子项目中完成我的后期功能,这个:

    postData(params){
    let headers = new Headers();
     headers.append('Content-type','application/json');
     return this.http.post(this.api,params,{
     headers: headers
     }).map(
     (res:Response) => {return res.json();}
      );

       }

这种方式>

          postData(params){           
          let headers = new Headers({'Content-type' : 'application/x-www-form-urlencoded'});
          return this.http.post(this.api,params,{
          headers: headers,
          method: 'POST'
          }).map(
          (res:Response) => {return res.json();}
          );

           }

我得到http 400错误的第一种方式,第二种方式我得到415错误。我在这里失踪了什么?

1 个答案:

答案 0 :(得分:1)

您收到415错误,因为服务器需要application / json,并且您将内容类型设置为application / x-www-form-urlencoded。

您得到400,因为您发送的数据无效:服务器需要一些特定的JSON结构和值,并且您正在发送其他内容。您应该在响应中出现错误消息,告知错误。检查你发送的内容,并检查Oferta的结构应该是什么。

请注意,将content-type标头设置为application / json是没用的,因为Angular会在发布对象时为您执行此操作。