I'm writing a wrapper REST API (say API X) for an available REST API (say API Y) written in Apache CXF. For the wrapper I'm using CXF Webclient. This is how I call Y from X.
@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);
}
}
Here, User class is copied from Y to X because I can't use Y as a dependency for X. The only difference is the package name. Now when I send a request, I get a class cast exception at 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
May be that's becuase of the class package name is different?
Can someone please help me to get the response to User object?
Looks like your response is in JSON format, that right? You need to convert the stream of JSON bytes in the response to a Java Class. You are trying to cast the Stream Class to your User Class which obviously won't work. You need to parse the JSON from the data stream and then deserialize the JSON into your User Class. There are libraries that can help including Jackson and GSON
This guy has a simple example using Jackson ObjectMapper class - the ObjectMapper class has a readValue method that includes an InputStream parameter.