4

我正在为用 Apache CXF 编写的可用 REST API(比如 API Y)编写一个包装 REST API(比如 API X)。对于包装器,我使用的是 CXF Webclient。这就是我从 X 中调用 Y 的方式。

@GET
@Path("{userName}")
public Response getUser(@PathParam("userName") String userName) {
    try {
        WebClient client 
                   = WebClient.create("https://localhost:8080/um/services/um");
        Response response = client.path("users/" + userName)
                                  .accept(MediaType.APPLICATION_JSON)
                                  .get();
        User user = (User) response.getEntity();
        return Response.ok(user).build();
    } catch (Exception e) {
        return handleResponse(ResponseStatus.FAILED, e);
    }
}    

在这里,用户类从 Y 复制到 X,因为我不能使用 Y 作为 X 的依赖项。唯一的区别是包名。现在,当我发送请求时,我在User user = (User) response.getEntity();.

java.lang.ClassCastException: sun.net.www.protocol.http.HttpURLConnection$HttpInputStream cannot be cast to org.comp.rest.api.bean.User

可能是因为类包名称不同?

有人可以帮我得到对用户对象的响应吗?

4

3 回答 3

2

看起来您的回复是 JSON 格式的,对吗?您需要将响应中的 JSON 字节流转换为 Java 类。您正在尝试将 Stream 类转换为您的用户类,这显然是行不通的。您需要从数据流中解析 JSON,然后将 JSON 反序列化为您的用户类。有一些图书馆可以提供帮助,包括JacksonGSON

这个人有一个使用 Jackson ObjectMapper 类的简单示例——ObjectMapper 类有一个包含 InputStream 参数的readValue 方法。

于 2014-10-23T11:32:03.153 回答
1

杰克逊提供者是一个解决方案:

 List<Object> providers = new ArrayList<Object>();
 providers.add(new JacksonJaxbJsonProvider());
 WebClient client = WebClient.create("https://localhost:8080/um/services/um", providers);
 User user = client.get(User.class);
于 2016-02-12T09:27:40.243 回答
0

不需要做任何额外的事情。

如果是GET方法

 TypeOfObject response = client.path("users/" + userName)
                              .accept(MediaType.APPLICATION_JSON)
                              .get(TypeOfObject.class);

如果是POST方法

TypeOfObject response = client.path("users/" + userName)
                              .accept(MediaType.APPLICATION_JSON)
                              .post(instatanceOfTypeOfObject, TypeOfObject.class);
于 2015-10-26T11:35:36.453 回答