Java API / 球衣放置方法
Java API / Jersey put method
这是我在 Java 中的第一个 API,所以请记住这一点 ;) 我有 Controller.class 我现在保留所有方法的地方(我稍后会清理它;))。就 GET 方法的完美工作而言,当我想创建新用户时,我遇到了 PUT 方法的问题 - 它不起作用。有什么帮助吗?和建议原因 - 正如我所说 - 我是新手 API ;)
所以这是我的 controller.class :
@Path("/api")
public class Controller {
List<Post> mBartoszPosts;
List<Post> mFelipePosts;
List<Post> mShawnPosts;
List<Post> mDavidPosts;
List<Post> mGraziellaPosts;
List<Post> mAllPosts;
List<User> mUsers;
User bartosz;
User felipe;
User shawn;
User david;
User graziella;
@Path("/user/{id}")
@GET
@Produces("application/json")
public Response getUser(@PathParam("id")int id) {
setUpUsers();
System.out.println("Liczba osob : " + mUsers.size());
for(User user : mUsers) {
if(id == user.getId()) {
String result = user.toString();
return Response.status(200).entity(user).build();
}
}
return null;
}
@Path("/post/{post_id}")
@GET
@Produces("application/json")
public Response getPost(@PathParam("post_id")int post_id) {
setUpUsers();
System.out.println("Liczba osob : " + mUsers.size());
for(Post post : mAllPosts) {
if(post_id == post.getId()) {
String result = post.toString();
return Response.status(200).entity(post).build();
}
}
return null;
}
@Path("/posts")
@GET
@Produces("application/json")
public Response getPosts() {
setUpUsers();
String response = new Gson().toJson(mAllPosts );
return Response.status(200).entity(response).build();
}
@PUT
@Path("user/new/{id}/{post}")
@Consumes(MediaType.APPLICATION_XML)
@Produces(MediaType.APPLICATION_XML)
public Response updateEmployeeById(@PathParam("id") Integer id,@PathParam("post") String userPost)
{
List<Post>userPosts = new ArrayList();
Post post = new Post(99,userPost,"Bartosz");
userPosts.add(post);
User updatedEmployee = new User(id,"Bartek","Szlapa",userPosts);
if(updatedEmployee.getName() == null) {
return Response.status(400).entity("Please provide the employee name !!").build();
}
updatedEmployee.setId(id);
updatedEmployee.setName(updatedEmployee.getName());
System.out.println(updatedEmployee.getName());
return Response.ok().entity(updatedEmployee).build();
}
public int maxValue(int array[]){
int max = Arrays.stream(array).max().getAsInt();
return max;
}
}
如您所见,最后一个方法是 PUT,但它不起作用:这是我的测试客户端:
public class Test {
public static void main(String[] args) {
// TODO Auto-generated method stub
Client client = ClientBuilder.newClient( new ClientConfig().register( Controller.class ) );
WebTarget webTarget = client.target("http://localhost:8080/JerseyDemos/rest").path("api").path("user").path("new").path("77");
List<Post>userPosts = new ArrayList();
Post post = new Post(99,"Bartek Szlapa","Testing post ...");
userPosts.add(post);
User emp = new User(99,"Bartek","Szlapa",userPosts);
Invocation.Builder invocationBuilder = webTarget.request(MediaType.APPLICATION_XML);
Response response = invocationBuilder.put(Entity.entity(emp, MediaType.APPLICATION_XML));
User user = response.readEntity(User.class);
System.out.println(response.getStatus());
System.out.println(user);
}
}
最后是我的错误:
Exception in thread "main" org.glassfish.jersey.message.internal.MessageBodyProviderNotFoundException: MessageBodyWriter not found for media type=application/xml, type=class entities.User, genericType=class entities.User.
at org.glassfish.jersey.message.internal.WriterInterceptorExecutor$TerminalWriterInterceptor.aroundWriteTo(WriterInterceptorExecutor.java:248)
at org.glassfish.jersey.message.internal.WriterInterceptorExecutor.proceed(WriterInterceptorExecutor.java:163)
at org.glassfish.jersey.message.internal.MessageBodyFactory.writeTo(MessageBodyFactory.java:1135)
at org.glassfish.jersey.client.ClientRequest.doWriteEntity(ClientRequest.java:516)
at org.glassfish.jersey.client.ClientRequest.writeEntity(ClientRequest.java:498)
at org.glassfish.jersey.client.internal.HttpUrlConnector._apply(HttpUrlConnector.java:384)
at org.glassfish.jersey.client.internal.HttpUrlConnector.apply(HttpUrlConnector.java:282)
at org.glassfish.jersey.client.ClientRuntime.invoke(ClientRuntime.java:278)
at org.glassfish.jersey.client.JerseyInvocation.lambda$invoke[=14=](JerseyInvocation.java:753)
at org.glassfish.jersey.internal.Errors.process(Errors.java:316)
at org.glassfish.jersey.internal.Errors.process(Errors.java:298)
at org.glassfish.jersey.internal.Errors.process(Errors.java:229)
at org.glassfish.jersey.process.internal.RequestScope.runInScope(RequestScope.java:414)
at org.glassfish.jersey.client.JerseyInvocation.invoke(JerseyInvocation.java:752)
at org.glassfish.jersey.client.JerseyInvocation$Builder.method(JerseyInvocation.java:445)
at org.glassfish.jersey.client.JerseyInvocation$Builder.put(JerseyInvocation.java:334)
at test.Test.main(Test.java:33)
在此先感谢您的帮助!
您的客户端代码中似乎有 2 个问题 -
要消除此错误,您应该在 class 路径中添加 jersey-media-jaxb
JAR
。如果您使用的是 Maven,请在 pom.xml
-
中添加以下依赖项
<dependency>
<groupId>org.glassfish.jersey.media</groupId>
<artifactId>jersey-media-jaxb</artifactId>
<version>${jersey.version}</version>
</dependency>
根据您的 PUT
方法 API 规范 -
public Response updateEmployeeById(@PathParam("id") Integer id,@PathParam("post") String userPost) {
您的 REST 服务只需要 path parameter
id
和 post
。不需要其他输入。但是,在您的客户端代码中,您在调用 API -
时发送 User
class 对象 emp
对象
Response response = invocationBuilder.put(Entity.entity(emp, MediaType.APPLICATION_XML));
由于您没有在 API 中收到此 emp
对象,因此此数据将会丢失。因此,您应该更新 API 以接受请求中的 User
class 对象,或者不要从您的客户端代码发送此对象。
这是我在 Java 中的第一个 API,所以请记住这一点 ;) 我有 Controller.class 我现在保留所有方法的地方(我稍后会清理它;))。就 GET 方法的完美工作而言,当我想创建新用户时,我遇到了 PUT 方法的问题 - 它不起作用。有什么帮助吗?和建议原因 - 正如我所说 - 我是新手 API ;)
所以这是我的 controller.class :
@Path("/api")
public class Controller {
List<Post> mBartoszPosts;
List<Post> mFelipePosts;
List<Post> mShawnPosts;
List<Post> mDavidPosts;
List<Post> mGraziellaPosts;
List<Post> mAllPosts;
List<User> mUsers;
User bartosz;
User felipe;
User shawn;
User david;
User graziella;
@Path("/user/{id}")
@GET
@Produces("application/json")
public Response getUser(@PathParam("id")int id) {
setUpUsers();
System.out.println("Liczba osob : " + mUsers.size());
for(User user : mUsers) {
if(id == user.getId()) {
String result = user.toString();
return Response.status(200).entity(user).build();
}
}
return null;
}
@Path("/post/{post_id}")
@GET
@Produces("application/json")
public Response getPost(@PathParam("post_id")int post_id) {
setUpUsers();
System.out.println("Liczba osob : " + mUsers.size());
for(Post post : mAllPosts) {
if(post_id == post.getId()) {
String result = post.toString();
return Response.status(200).entity(post).build();
}
}
return null;
}
@Path("/posts")
@GET
@Produces("application/json")
public Response getPosts() {
setUpUsers();
String response = new Gson().toJson(mAllPosts );
return Response.status(200).entity(response).build();
}
@PUT
@Path("user/new/{id}/{post}")
@Consumes(MediaType.APPLICATION_XML)
@Produces(MediaType.APPLICATION_XML)
public Response updateEmployeeById(@PathParam("id") Integer id,@PathParam("post") String userPost)
{
List<Post>userPosts = new ArrayList();
Post post = new Post(99,userPost,"Bartosz");
userPosts.add(post);
User updatedEmployee = new User(id,"Bartek","Szlapa",userPosts);
if(updatedEmployee.getName() == null) {
return Response.status(400).entity("Please provide the employee name !!").build();
}
updatedEmployee.setId(id);
updatedEmployee.setName(updatedEmployee.getName());
System.out.println(updatedEmployee.getName());
return Response.ok().entity(updatedEmployee).build();
}
public int maxValue(int array[]){
int max = Arrays.stream(array).max().getAsInt();
return max;
}
}
如您所见,最后一个方法是 PUT,但它不起作用:这是我的测试客户端:
public class Test {
public static void main(String[] args) {
// TODO Auto-generated method stub
Client client = ClientBuilder.newClient( new ClientConfig().register( Controller.class ) );
WebTarget webTarget = client.target("http://localhost:8080/JerseyDemos/rest").path("api").path("user").path("new").path("77");
List<Post>userPosts = new ArrayList();
Post post = new Post(99,"Bartek Szlapa","Testing post ...");
userPosts.add(post);
User emp = new User(99,"Bartek","Szlapa",userPosts);
Invocation.Builder invocationBuilder = webTarget.request(MediaType.APPLICATION_XML);
Response response = invocationBuilder.put(Entity.entity(emp, MediaType.APPLICATION_XML));
User user = response.readEntity(User.class);
System.out.println(response.getStatus());
System.out.println(user);
}
}
最后是我的错误:
Exception in thread "main" org.glassfish.jersey.message.internal.MessageBodyProviderNotFoundException: MessageBodyWriter not found for media type=application/xml, type=class entities.User, genericType=class entities.User.
at org.glassfish.jersey.message.internal.WriterInterceptorExecutor$TerminalWriterInterceptor.aroundWriteTo(WriterInterceptorExecutor.java:248)
at org.glassfish.jersey.message.internal.WriterInterceptorExecutor.proceed(WriterInterceptorExecutor.java:163)
at org.glassfish.jersey.message.internal.MessageBodyFactory.writeTo(MessageBodyFactory.java:1135)
at org.glassfish.jersey.client.ClientRequest.doWriteEntity(ClientRequest.java:516)
at org.glassfish.jersey.client.ClientRequest.writeEntity(ClientRequest.java:498)
at org.glassfish.jersey.client.internal.HttpUrlConnector._apply(HttpUrlConnector.java:384)
at org.glassfish.jersey.client.internal.HttpUrlConnector.apply(HttpUrlConnector.java:282)
at org.glassfish.jersey.client.ClientRuntime.invoke(ClientRuntime.java:278)
at org.glassfish.jersey.client.JerseyInvocation.lambda$invoke[=14=](JerseyInvocation.java:753)
at org.glassfish.jersey.internal.Errors.process(Errors.java:316)
at org.glassfish.jersey.internal.Errors.process(Errors.java:298)
at org.glassfish.jersey.internal.Errors.process(Errors.java:229)
at org.glassfish.jersey.process.internal.RequestScope.runInScope(RequestScope.java:414)
at org.glassfish.jersey.client.JerseyInvocation.invoke(JerseyInvocation.java:752)
at org.glassfish.jersey.client.JerseyInvocation$Builder.method(JerseyInvocation.java:445)
at org.glassfish.jersey.client.JerseyInvocation$Builder.put(JerseyInvocation.java:334)
at test.Test.main(Test.java:33)
在此先感谢您的帮助!
您的客户端代码中似乎有 2 个问题 -
要消除此错误,您应该在 class 路径中添加
中添加以下依赖项jersey-media-jaxb
JAR
。如果您使用的是 Maven,请在pom.xml
-<dependency> <groupId>org.glassfish.jersey.media</groupId> <artifactId>jersey-media-jaxb</artifactId> <version>${jersey.version}</version> </dependency>
根据您的
PUT
方法 API 规范 -
public Response updateEmployeeById(@PathParam("id") Integer id,@PathParam("post") String userPost) {
您的 REST 服务只需要 path parameter
id
和 post
。不需要其他输入。但是,在您的客户端代码中,您在调用 API -
User
class 对象 emp
对象
Response response = invocationBuilder.put(Entity.entity(emp, MediaType.APPLICATION_XML));
由于您没有在 API 中收到此 emp
对象,因此此数据将会丢失。因此,您应该更新 API 以接受请求中的 User
class 对象,或者不要从您的客户端代码发送此对象。