2

当我在客户端使用 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。

4

2 回答 2

2

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

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

于 2018-12-11T07:48:07.497 回答
1

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

 @Consumes(MediaType.APPLICATION_JSON)

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

于 2018-02-04T15:01:53.620 回答