REST Web 服务返回 415 - 不支持的媒体类型

2022-09-02 05:15:39

我使用jax-rs和jage创建了一个REST Web服务,它应该在POST请求上使用JSON。我的 Web 服务类如下所示:

@Path("/webhookservice")
public class Webhook {

    @POST
    @Consumes(MediaType.APPLICATION_JSON)
    public Response readData (Song song) {

        // Prints out the song info
        System.out.println("SONG INFO \n=======================");
        System.out.println("songname: " + song.getSongname());
        System.out.println("artist: " + song.getArtist());

        // Repsonse with a HTTP 200 OK
        Response response = Response.status(200).build();
        return response;

    }

}

我的歌课:

public class Song {

    private String songname;
    private String artist;

    public String getSongname () { return this.songname; }
    public String getArtist () { return this.artist; }

    public void setSongname (String songname) { this.songname = songname; }
    public void setArtist (String artist) { this.artist = artist; }

}

我的网页.xml(如果需要)

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xmlns="http://java.sun.com/xml/ns/javaee"
    xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd"
    id="WebApp_ID" version="3.0">

    <servlet>
        <servlet-name>SnapScan-Webhook</servlet-name>
        <servlet-class>com.sun.jersey.spi.container.servlet.ServletContainer</servlet-class>
        <init-param>
            <param-name>com.sun.jersey.config.property.packages</param-name>
            <param-value>za.co.lancet.service</param-value>
        </init-param>
        <init-param>
            <param-name>com.sun.jersey.api.json.POJOMappingFeature</param-name>
            <param-value>true</param-value>
        </init-param>
        <load-on-startup>1</load-on-startup>
    </servlet>

    <servlet-mapping>
        <servlet-name>SnapScan-Webhook</servlet-name>
        <url-pattern>/*</url-pattern>
    </servlet-mapping>

</web-app>

我正在使用RESTClient一点点,好吧,休息客户端...以下是我发送的内容的屏幕截图:

enter image description here

当我发送该消息时,我收到“415 不支持的媒体类型”错误。有人知道为什么吗?


答案 1

您需要发送请求标头 。似乎 REST-Client 不会自动为您添加此标头。Content-Type: application/json


答案 2

正如其他人所指出的,您缺少正确的标头。添加到“标题”:Content-Type: application/jsonenter image description here