我有一个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不能为我工作吗?
解决方法:
您正在执行:
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 );
不要使用旧的泽西捆绑图书馆.下载2.0版本:
https://jersey.java.net/download.html
将所有库(库和ext库)添加到您的类路径中.
接下来,您需要在类路径中使用jackson软件包:
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
您的服务等级应与此类似:
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.