无法将JSON对象发送到Rest Web服务

时间:2014-01-20 22:45:43

标签: java json rest jersey pojo

我有一个REST Web服务配置如下:

@Path("/users")
public class UserManager {

@Context
UriInfo uriInfo;

@POST
@Consumes("application/json")
public void createUser(User user) {
    URI uri = uriInfo.getAbsolutePathBuilder().path(user.getUserName())
            .build();
    Response res = Response.created(uri).build();
    try {
        MongoDbDataAccess.getInstance().addUser(user);
    } catch (Exception e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
}

我的Tomcat服务器配置如下:

<servlet>
  <servlet-name>Jersey REST Service</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>anyq.server.anyq.manager</param-value>
  </init-param>
  <load-on-startup>1</load-on-startup>
</servlet>

<servlet-mapping>
   <servlet-name>Jersey REST Service</servlet-name>
   <url-pattern>/rest/*</url-pattern>
</servlet-mapping>

我创建的POJO如下所示:

@XmlRootElement
public class User {

private long userId;
private String userName;
private String userPassword;

public User() {
    super();
}

public User(long userId, String userName, String userPassword) {
    super();
    this.userId = userId;
    this.userName = userName;
    this.userPassword = userPassword;
}

public long getUserId() {
    return userId;
}

public void setUserId(long userId) {
    this.userId = userId;
}

public String getUserName() {
    return userName;
}

public void setUserName(String userName) {
    this.userName = userName;
}

public String getUserPassword() {
    return userPassword;
}

public void setUserPassword(String userPassword) {
    this.userPassword = userPassword;
}

}

我创建了一个测试客户端,以便测试createUser方法:

public class tester {

public static void main(String[] args) throws UnknownHostException {

    String USER_URI = "http://localhost:8080/AnyAppserver/rest/users";
    User user = new User((long) 451, "mosssi", "464asd64");

    Client client = Client.create();

    WebResource r = client.resource(USER_URI);

    ClientResponse response = r.accept(MediaType.APPLICATION_JSON).post(
            ClientResponse.class, user);


}

但是我收到以下错误:

POST http://localhost:8080/AnyAppserver/rest/users returned a response status of 415 Unsupported Media Type

奇怪的问题是,当我将所有内容更改为appliction / xml时,它可以完美地运行

任何想法为什么Json不适合我?

1 个答案:

答案 0 :(得分:3)

你在做:

User user = new User((long) 451, "mosssi", "464asd64");

ClientResponse response = r.accept(MediaType.APPLICATION_JSON).post(ClientResponse.class, user);

这是错的。您应该向您的服务发送一个真正的JSON字符串。

获取JSON解析器,例如:gson,并执行以下操作:

User user = new User(451, "mosssi", "464asd64");
String request = gson.toJson(user);
ClientResponse response = r.type(MediaType.APPLICATION_JSON).post(ClientResponse.class, request );

不要使用旧的Jersey-bundle库。下载2.0版本: https://jersey.java.net/download.html

将所有库(lib和ext库)添加到类路径中。

接下来,您需要在类路径中使用jackson包: 杰克逊的注解 - 2.2.2.jar 杰克逊核心2.2.2.jar 杰克逊 - 数据绑定 - 2.2.2.jar 杰克逊 - JAXRS碱基2.2.1.jar 杰克逊JAXRS JSON的提供商 - 2.2.1.jar 杰克逊模块-JAXB的注解-2.2.2.jar

您的服务类应与此类似:

package anyq.server.anyq.manager;

import javax.ws.rs.Consumes;
import javax.ws.rs.POST;
import javax.ws.rs.Path;
import javax.ws.rs.core.Context;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;
import javax.ws.rs.core.UriInfo;

import anyq.server.common.bean.User;

@Path("/users")
public class AnyQUserManager {

@Context
UriInfo uriInfo;

@POST
@Consumes(MediaType.APPLICATION_JSON)
public Response createUser(User user) {
    System.out.println("HELLO WORLD");
    return Response.status(666).entity("Hello world").build();
}
}

最后,您的web.xml应如下所示:

<web-app xmlns="http://java.sun.com/xml/ns/j2ee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd"
version="2.4">

<servlet>
    <servlet-name>Jersey REST Service</servlet-name>
    <servlet-class>org.glassfish.jersey.servlet.ServletContainer</servlet-class>
    <init-param>
        <param-name>jersey.config.server.provider.packages</param-name>
        <param-value>anyq.server.anyq.manager, com.fasterxml.jackson.jaxrs.json</param-value>
    </init-param>
    <load-on-startup>1</load-on-startup>
</servlet>

<servlet-mapping>
    <servlet-name>Jersey REST Service</servlet-name>
    <url-pattern>/rest/*</url-pattern>
</servlet-mapping>

在您的客户端类中,执行以下操作:

    String USER_URI = "http://localhost:8080/AnyQserver/rest/users";
    User user = new anyq.server.common.bean.User();
    user.setUserId(15);
    user.setUserName("asd");
    user.setUserPassword("asd");

    Client client = Client.create();
    String request = new Gson().toJson(user);
    System.out.println(request);
    WebResource r = client.resource(USER_URI);
    ClientResponse response = r.type(MediaType.APPLICATION_JSON).post(
            ClientResponse.class, request);
    System.out.println(response.getStatus());

重启服务器并运行客户端。如果一切顺利,服务器应该打印:

INFO: Server startup in 2256 ms
HELLO WORLD

和客户:

{"userId":15,"userName":"asd","userPassword":"asd"}
666
祝你好运!

另外,我真的很想你迁移到maven。