POST 到 Jersey REST 服务收到错误 415 不支持的媒体类型 [英] POST to Jersey REST service getting error 415 Unsupported Media Type

查看:32
本文介绍了POST 到 Jersey REST 服务收到错误 415 不支持的媒体类型的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在 Jersey 和 Tomcat 中使用 JAX-RS Web 应用程序.获取请求很好,但是当我尝试发布 JSON 时,我收到 HTTP 状态 415 - 不支持的媒体类型.

I am using a JAX-RS web application with Jersey and Tomcat. Get requests are fine however when I try to post JSON I get an HTTP status 415 - Unsupported Media Type.

这是我的简单 HelloWorld.java:

Here is my simple HelloWorld.java:

package service;

import javax.ws.rs.*;

@Path("hello")
public class HelloWorld {
    @GET
    @Produces("text/plain")
    public String get() {
        return "hello world";
    }

    @POST
    @Consumes("application/json")
    public String post(JS input) {
        return input.hello;
    }

    public static class JS {
        public String hello;
    }
}

这是我在 Postman 中尝试的请求(带有application/json"标头):

Here is the request I try in Postman (with 'application/json' header):

这是带有库的项目布局:

Here is the project layout with libraries:

我正在使用:

  • Java 7 x64
  • 球衣 2.17
  • Tomcat 7.0.62 x64

谢谢!

推荐答案

Jersey 发行版并未提供开箱即用的 JSON/POJO 支持.您需要添加依赖项/jar.

The Jersey distribution doesn't come with JSON/POJO support out the box. You need to add the dependencies/jars.

添加所有这些

使用 Maven,下面将把上面的所有内容都拉进来

With Maven, below will pull all the above in

<dependency>
    <groupId>org.glassfish.jersey.media</groupId>
    <artifactId>jersey-media-json-jackson</artifactId>
    <version>2.17</version>
</dependency>

对于未来不使用 Jersey 2.17(并直接使用 jars 而不是 Maven)的读者,您可以访问 此处 查找您正在使用的 Jersey 版本,并查看您需要哪些传递依赖版本.此 Jersey 依赖项的当前版本使用 Jackson 2.3.2.这是你需要注意的主要事情.

For any future readers not using Jersey 2.17 (and using jars directly instead of Maven), you can go here to find the Jersey version you are using, and see what transitive dependency versions you need. The current version of this Jersey dependency uses Jackson 2.3.2. That's the main thing you need to look out for.

这篇关于POST 到 Jersey REST 服务收到错误 415 不支持的媒体类型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆