【问题标题】:Error 415 on POST with jersey带有运动衫的 POST 错误 415
【发布时间】:2018-07-14 12:12:29
【问题描述】:

当我在客户端使用 POST 时,我收到以下错误。

HTTP Status 415 - Unsupported Media Type
Type: Status Report
Message: Unsupported Media Type
Description: The origin server is refusing to service the request because the payload is in a format not supported by this method on the target resource.

我一直在尝试解决许多帖子后的问题。我希望我没有使用不兼容的解决方案。

GET 部分工作正常,我正在使用 Gson 转换为 JSON。

最初我的代码没有从应用程序扩展,但它是另一个帖子中解决方案的一部分,他们在其中注册了 Jackson 以获得 JSON 支持。

这是我的服务类的代码:

package com.tutorialspoint;

import java.io.IOException;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

import javax.servlet.http.HttpServletResponse;
import javax.ws.rs.Consumes;
import javax.ws.rs.FormParam;
import javax.ws.rs.GET;
import javax.ws.rs.POST;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
import javax.ws.rs.core.Application;
import javax.ws.rs.core.Context;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;
import javax.ws.rs.core.Response.Status;

import org.glassfish.jersey.jackson.JacksonFeature;

import com.google.gson.Gson;

@Path("/UserService")

public class UserService extends Application
{
    UserDao userDao = new UserDao();

    @Override
    public Set<Class<?>> getClasses()
    {
        Set<Class<?>> classes = new HashSet<>();
        classes.add(JacksonFeature.class);

        return classes;
    }

    @GET
    @Path("/users")
    @Produces(MediaType.APPLICATION_JSON)
    public Response getUsers()
    {
        List<User> userList = userDao.getAllUsers();
        Response.Status responseStatus = Response.Status.ACCEPTED;

        return getJSONResponse(responseStatus, userList);
    }

    @POST
    @Path("/users")
    @Produces(MediaType.APPLICATION_JSON)
    @Consumes(MediaType.APPLICATION_JSON)
    public Response createUser
    (
            @FormParam("id") int id,
            @FormParam("name") String name,
            @FormParam("profession") String profession,
            @Context HttpServletResponse servletResponse) throws IOException
    {
        User user = new User(id, name, profession);

        boolean userAdded = userDao.addUser(user);

        if(userAdded)
        {
            return getJSONResponse(Status.CREATED, id);
        }

        //Should be changed to an error response later.
        return getJSONResponse(Status.CREATED, id);
    }

    public static Response getJSONResponse(Response.Status status, Object entity)
    {
        String json = new Gson().toJson(entity);

        return Response.status(status).entity(json).header("Access-Control-Allow-Origin", "*").build();
    }
}

这是客户端发出的请求。它是在 cient 计算机上使用 linux 的 nc 命令捕获的。

POST /UserManagement/rest/UserService/users HTTP/1.1
Host: localhost:58585
Connection: keep-alive
Content-Length: 47
Accept: application/json
Origin: http://localhost:4200
User-Agent: Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/64.0.3282.119 Safari/537.36
content-type: text/plain
Referer: http://localhost:4200/persons
Accept-Encoding: gzip, deflate, br
Accept-Language: en-US,en;q=0.9

{"id":1,"name":"Mahesh","profession":"Teacher"}

提前致谢。


编辑 01

所以你需要发送带有名称 Content-type 和值 application/json 而不是 text/plain 的标头

我按照@user7294900 的建议使用 content-type: application/json 发送了请求。 (我无法通过 Angular 2 中的客户端正确发送它,所以我改用 telnet)

POST /UserManagement/rest/UserService/users HTTP/1.1
Host: localhost:58585
Connection: keep-alive
Content-Length: 47
Accept: application/json
Origin: http://localhost:4200
User-Agent: Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/64.0.3282.119 Safari/537.36
content-type: application/json
Referer: http://localhost:4200/persons
Accept-Encoding: gzip, deflate, br
Accept-Language: en-US,en;q=0.9

{"id":1,"name":"Mahesh","profession":"Teacher"}

之后我得到了@braunpet 所述的错误 500

您希望您的客户端发送 JSON,但后端需要一个 HTML 表单 (@FormParam),它作为媒体类型 application/x-www-form-urlencoded 发送。

之后我像这样更改了我的服务类(使用用户作为 createUser 的参数):

package com.tutorialspoint;

import java.io.IOException;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

//import javax.servlet.http.HttpServletResponse;
import javax.ws.rs.Consumes;
//import javax.ws.rs.FormParam;
import javax.ws.rs.GET;
import javax.ws.rs.POST;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
import javax.ws.rs.core.Application;
//import javax.ws.rs.core.Context;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;
import javax.ws.rs.core.Response.Status;

import org.glassfish.jersey.jackson.JacksonFeature;

import com.google.gson.Gson;

@Path("/UserService")

public class UserService extends Application
{
    UserDao userDao = new UserDao();

    @Override
    public Set<Class<?>> getClasses()
    {
        Set<Class<?>> classes = new HashSet<>();
        classes.add(JacksonFeature.class);

        return classes;
    }

    @GET
    @Path("/users")
    @Produces(MediaType.APPLICATION_JSON)
    public Response getUsers()
    {
        List<User> userList = userDao.getAllUsers();
        Response.Status responseStatus = Response.Status.ACCEPTED;

        return getJSONResponse(responseStatus, userList);
    }

    @POST
    @Path("/users")
    @Produces(MediaType.APPLICATION_JSON)
    @Consumes(MediaType.APPLICATION_JSON)
    public Response createUser
    (
            User user
//          @FormParam("id") int id,
//          @FormParam("name") String name,
//          @FormParam("profession") String profession,
//          @Context HttpServletResponse servletResponse
    ) throws IOException
    {
//      User user = new User(id, name, profession);

        boolean userAdded = userDao.addUser(user);

        if(userAdded)
        {
//          return getJSONResponse(Status.CREATED, id);
            return getJSONResponse(Status.CREATED, user.getId());
        }

        //Should be changed to an error response later.
//      return getJSONResponse(Status.CREATED, id);
        return getJSONResponse(Status.CREATED, user.getId());
    }

    public static Response getJSONResponse(Response.Status status, Object entity)
    {
        String json = new Gson().toJson(entity);

        return Response.status(status).entity(json).header("Access-Control-Allow-Origin", "*").build();
    }
}

然后返回错误 415。

【问题讨论】:

  • 你的方法createUser有问题。您希望您的客户端发送 JSON,但后端需要一个 HTML 表单 (@FormParam),它作为媒体类型 application/x-www-form-urlencoded 发送。如果您的 JSON 提供程序与 Jersey 集成,您应该可以编写 Response createUser( User user )。

标签: java json post jersey http-status-code-415


【解决方案1】:

确保您的项目中有此依赖项

编译组:'org.glassfish.jersey.media',名称: 'jersey-media-json-jackson',版本:'2.27'

【讨论】:

  • 有时简单的错误最难调试! :)
【解决方案2】:

由于您的代码中有以下定义,您应该声明发送 json 内容类型:

 @Consumes(MediaType.APPLICATION_JSON)

所以您需要发送名称为Content-type 和值application/json 的标头而不是text/plain

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2013-03-20
    • 2014-08-14
    • 2017-09-07
    • 2019-01-26
    • 1970-01-01
    • 1970-01-01
    • 2017-10-21
    • 2018-06-13
    相关资源
    最近更新 更多