无法使用POST方法返回JSON对象

时间:2018-08-27 19:52:30

标签: json jersey-2.0 moxy

我正在编写Jersey 2 Restful Web服务。 这是服务类:

package com.Test.PS;
import java.io.IOException;
import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.QueryParam;
import javax.ws.rs.Consumes;
import javax.ws.rs.POST;

import com.Test.Exchange.*; // Here class UserInfo is defined

@Path("/ps")
public class TestService {
    private UserInfo ui;
    public TestService () throws IOException {
        ui = new UserInfo();
    }
    public TestService (String uid) throws IOException {
        UserInfo ui = ObjectFileStore.serializeDataIn(uid);
    }

    public TestService (UserInfo ui) throws IOException {
        this.ui = ui;
        ObjectFileStore.serializeDataOut(ui);
    }

    @GET
    @Produces(MediaType.TEXT_HTML)
    public String sayHelloHTML(@QueryParam("uid") String uid) {     
        String resource="<h1> Hi '" + uid + "'. </h1>";
        return resource;
    }

    @POST
    @Consumes(MediaType.APPLICATION_JSON)
    @Produces(MediaType.APPLICATION_JSON)
    public UserInfo postNK(@QueryParam("asid") String asid, UserInfo u) {
        return ui;
    }
}

以下是Maven依赖项:

<dependency>
  <groupId>org.glassfish.jersey.containers</groupId>
  <artifactId>jersey-container-servlet-core</artifactId>
  <version>${version.jersey}</version>
</dependency>

<dependency>
  <groupId>org.glassfish.jersey.inject</groupId>
  <artifactId>jersey-hk2</artifactId>
  <version>${version.jersey}</version>
</dependency>

<!--  JSON Support (MOXy) -->
<dependency>
  <groupId>org.glassfish.jersey.media</groupId>
  <artifactId>jersey-media-moxy</artifactId>
  <version>${version.jersey}</version>
</dependency>

最后,这是我的web.xml文件:

  <display-name>Test-PS</display-name>
  <welcome-file-list>
    <welcome-file>index.html</welcome-file>
  </welcome-file-list>

  <servlet>
    <servlet-name>Test-PS</servlet-name>
    <servlet-class>org.glassfish.jersey.servlet.ServletContainer</servlet-class>

    <init-param>
      <param-name>jersey.config.server.provider.packages</param-name>
      <param-value>com.Test.PS</param-value>
    </init-param>

    <load-on-startup>1</load-on-startup>
  </servlet>

  <servlet-mapping>
    <servlet-name>Test-PS</servlet-name>
    <url-pattern>/rest/*</url-pattern>
  </servlet-mapping>
</web-app>

使用以下代码汇总post方法时,出现以下错误:

UserInfo n2k = new UserInfo();  
ClientConfig config = new ClientConfig(MOXyJsonProvider.class);
Client client = ClientBuilder.newClient(config);
String targetUrl = "http://localhost:8081/Test-PS";
WebTarget target = client.target(targetUrl);
Invocation.Builder invocationBuilder = target.path("rest").path("ps").queryParam("asid", ASID).request(MediaType.APPLICATION_JSON);
Response response = invocationBuilder.post(Entity.entity(n2k, MediaType.APPLICATION_JSON));
UserInfo ui = response.readEntity(UserInfo.class);
response.close();
client.close();

在控制台屏幕上,我看到:

org.glassfish.jersey.message.internal.MessageBodyProviderNotFoundException: MessageBodyReader not found for media type=text/html;charset=utf-8, type=class com.Exchange.UserInfo, genericType=class com.Exchange.UserInfo.
org.glassfish.jersey.message.internal.ReaderInterceptorExecutor$TerminalReaderInterceptor.aroundReadFrom(ReaderInterceptorExecutor.java:232)
org.glassfish.jersey.message.internal.ReaderInterceptorExecutor.proceed(ReaderInterceptorExecutor.java:156)
org.glassfish.jersey.message.internal.MessageBodyFactory.readFrom(MessageBodyFactory.java:1091)
org.glassfish.jersey.message.internal.InboundMessageContext.readEntity(InboundMessageContext.java:874)
org.glassfish.jersey.message.internal.InboundMessageContext.readEntity(InboundMessageContext.java:808)
org.glassfish.jersey.client.ClientResponse.readEntity(ClientResponse.java:321)
org.glassfish.jersey.client.InboundJaxrsResponse$1.call(InboundJaxrsResponse.java:115)
org.glassfish.jersey.internal.Errors.process(Errors.java:316)
org.glassfish.jersey.internal.Errors.process(Errors.java:298)
org.glassfish.jersey.internal.Errors.process(Errors.java:229)
org.glassfish.jersey.process.internal.RequestScope.runInScope(RequestScope.java:389)
org.glassfish.jersey.client.InboundJaxrsResponse.runInScopeIfPossible(InboundJaxrsResponse.java:264)
org.glassfish.jersey.client.InboundJaxrsResponse.readEntity(InboundJaxrsResponse.java:112)
com.AS.AuthenticatorService.Authenticate(AuthenticatorService.java:79)
org.apache.jsp.JSP.Authenticate_jsp._jspService(Authenticate_jsp.java:128)
org.apache.jasper.runtime.HttpJspBase.service(HttpJspBase.java:70)
javax.servlet.http.HttpServlet.service(HttpServlet.java:741)
org.apache.jasper.servlet.JspServletWrapper.service(JspServletWrapper.java:458)
org.apache.jasper.servlet.JspServlet.serviceJspFile(JspServlet.java:386)
org.apache.jasper.servlet.JspServlet.service(JspServlet.java:330)
javax.servlet.http.HttpServlet.service(HttpServlet.java:741)
org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:53)

服务器日志显示:     “ POST / Test-PS / rest / ps?asid = AS1 HTTP / 1.1” 500 1081

我已经尝试了许多针对此错误的解决方案,但没有一个可以解决!!

我还要补充一点,如果POST方法返回原始类型(例如String),而不是用户定义的原始类型(即UserInfo),它将起作用! UserInfo是一个序列化的类,具有以下字段:用户名,出生日期等。

2 个答案:

答案 0 :(得分:0)

您正在与事物融合。您的GET方法可以使用查询参数,而POST则不能。像这样更改您的发布方法:

@POST("{asid}")
@Consumes(MediaType.APPLICATION_JSON)
@Produces(MediaType.APPLICATION_JSON)
public UserInfo postNK(@PathParam("asid") String asid, UserInfo u) {
    return ui;
}

然后

Invocation.Builder invocationBuilder = target.path("rest").path("ps/" + ASID).request(MediaType.APPLICATION_JSON);

我曾经用jax-rs构建rest api,所以我想应该有另一种添加ASID参数的方法。

答案 1 :(得分:0)

哦,终于我明白了。确实是一个奇怪的人。 UserInfo 类中有一个名为 setUserInfo 的方法,该方法可以接受与以下代码所示的类类型相同的参数:

public void setUserInfo(UserInfo ui) {
    this.firstName = ui.getFirstName();
    this.lastName = ui.getFirstName();
    this.dateOfBirth = ui.getDateOfBirth();
    this.homeAddress = ui.getHomeAddress();
}

如果我删除它,一切都会顺利进行。重新添加后,我会遇到同样的异常。如果该类将作为Jersey JSON响应发送,则似乎禁止该类具有接受其类型的参数的方法。

我不知道为什么,但是这是我多次尝试的问题,而且每次添加该方法时,都会引发相同的异常!!!可能是一个错误!!!

您也可以尝试