【问题标题】:Error 415 Unsupported Media Type while trying to http.post from a ionic 3 project to a java webservice尝试从 ionic 3 项目 http.post 到 java webservice 时出现错误 415 Unsupported Media Type
【发布时间】:2018-04-05 20:52:03
【问题描述】:

我有一个使用 JERSEY 的 java 后端项目和一个用于前端的 ionic 3 项目。尽管 get 方法工作正常,但我无法让 post 方法工作。

这是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();

}

我尝试以两种不同的方式在我的 ionic 项目中执行我的 post 功能,这:

    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 错误的第二种方式。我在这里缺少什么?

【问题讨论】:

    标签: angular http jersey


    【解决方案1】:

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

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

    请注意,将 content-type 标头设置为 application/json 是没有用的,因为 Angular 在发布对象时会为您这样做。

    【讨论】:

    • 是的,你是对的,必须将 ngModel 名称设置为与 oferta 属性相同,现在工作正常! ty
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-07-14
    • 1970-01-01
    • 2017-08-16
    • 2012-04-19
    • 1970-01-01
    相关资源
    最近更新 更多