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

Unable to send JSON object to Rest web service(无法将 JSON 对象发送到 Rest Web 服务)

本文介绍了无法将 JSON 对象发送到 Rest Web 服务的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I have a REST web servce configure as the following:

@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服务器配置如下:

And My Tomcat server configure as the following:

<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 如下所示:

The POJO I create look like the following:

@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 方法:

I create the a test client in order to test the createUser method:

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 时,它可以完美运行

The wierd issue is when I change everything to appliction/xml it work perfectly

知道为什么 Json 不适合我吗?

Any Idea why Json doesnt work for me?

推荐答案

你在做:

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

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

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

It's wrong. You should send to your service a real JSON String.

获取 JSON 解析器,例如:gson,然后这样做:

Get JSON parser, for example: gson, and do this:

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

Don't use old Jersey-bundle library. Download 2.0 version: https://jersey.java.net/download.html

将所有库(lib 和 ext 库)添加到您的类路径.

add all libs (lib and ext libraries) to your classpath.

接下来,您需要在类路径中使用 jackson 包:jackson-annotations-2.2.2.jar杰克逊核心2.2.2.jarjackson-databind-2.2.2.jar杰克逊-jaxrs-base-2.2.1.jar杰克逊-jaxrs-json-provider-2.2.1.jarjackson-module-jaxb-annotations-2.2.2.jar

Next, you need the jackson packages in your classpath: jackson-annotations-2.2.2.jar jackson-core-2.2.2.jar jackson-databind-2.2.2.jar jackson-jaxrs-base-2.2.1.jar jackson-jaxrs-json-provider-2.2.1.jar jackson-module-jaxb-annotations-2.2.2.jar

您的服务类应该与此类似:

Your service class should be similiar to this:

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 应该如下所示:

And, finaly, your web.xml should look like:

<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>

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

In your client class, do this:

    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());

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

Restart server and run client. If everything went fine, server should print:

INFO: Server startup in 2256 ms
HELLO WORLD

和客户:

{"userId":15,"userName":"asd","userPassword":"asd"}
666

祝你好运!

另外,我真的建议你迁移到 Maven.

Also, I really sugest you to migrate to maven.

这篇关于无法将 JSON 对象发送到 Rest Web 服务的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!

本文标题为:无法将 JSON 对象发送到 Rest Web 服务

基础教程推荐