【问题标题】:Jax-RS response comes in HTML/text instead of JSONJax-RS 响应来自 HTML/文本而不是 JSON
【发布时间】:2019-05-06 23:11:12
【问题描述】:

我有一个前端反应应用程序,我在其中向 REST Jax-RS 后端服务器发出请求。

这是正在发送的请求

  deletePost = (post) =>{
return deleter(config.restUrl + `posts/${post}`)
 }

在这里,我得到了我的后端的标准 URL,带有一个“删除”功能,它只是一种标准化的提取删除方法(也适用于其他实体)。

这是我的 Jax-RS 资源:

@DELETE
@Consumes(APPLICATION_JSON)
@Produces(APPLICATION_JSON)
@Path("/{id: [0-9]+}")
public Response deletePost(@HeaderParam("authorization") String token, @PathParam("id") Integer id) throws ResourceNotFoundException, AuthenticationException
{
    AuthenticationContext authenticationContext = authenticationFacade.authenticateBearerHeader(token);
    Post                  post                  = postFacade.delete(authenticationContext, id);
    return Response.ok(gson.toJson(PostDTO.basic(post))).build();
}

问题是它给了我一个错误,说表单是 HTML/文本:

MessageBodyWriter not found for media type\u003dtext/html, type\u003dclass com.group3.sem3exam.rest.dto.PostDTO, genericType\u003dclass com.group3.sem3exam.rest.dto.PostDTO

由于暗示是PostDTO有错误,所以我去检查了将实体转换为数据传输对象的基本方法,以发送回客户端。

   public static PostDTO basic(Post post)
{
    return new PostDTO(
            post.getId(),
            post.getContents(),
            post.getCreatedAt(),
            null,
            ImageDTO.list(post.getImages(), ImageDTO::withoutUser)
    );
    }

这里它只是调用返回对象新实例的方法。

之前没见过这个错误,不知道怎么处理?

【问题讨论】:

  • 尝试将请求中的Accept头设置为application/json。
  • 检查是否为您的应用程序注册了消息正文编写器。如果您使用 Jersey 并希望使用 Jackson 作为正文编写器,您可能需要在您的 ApplicationConfigResourceConfig 类中添加 register(JacksonFeature.class);,当然这是在您的依赖项管理器中添加依赖项之后。

标签: java json rest jax-rs


【解决方案1】:

试试

return Response.status(Status.OK).entity(new Gson().toJson(PostDTO.basic(post))).build();

【讨论】:

  • 不幸的是仍然报错。正如怀疑的那样,差异并没有真正导致任何变化,因为功能是相同的。但 +1 表示努力。
猜你喜欢
  • 2017-04-29
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-07-17
  • 1970-01-01
  • 2016-09-20
  • 2018-12-19
相关资源
最近更新 更多