Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
370 views
in Technique[技术] by (71.8m points)

Microprofile java.lang.ClassCastException: sun.net.www.protocol.http.HttpURLConnection$HttpInputStream incompatible

I'm using microprofile 3.2 to call out to a rest webservice that returns a java bean in a Response entity. When I try to extract the bean from the response though I get a

java.lang.ClassCastException: sun.net.www.protocol.http.HttpURLConnection$HttpInputStream incompatible with <class>

error.

E.g.

My bean:

public class MyBean {
    private int id;
    public int getId() { return id; }
    public void setId(final int id) { this.id = id; }
}

REST WS api interface:

@GET
@Path("/{id}")
Response getBean(@PathParam("id") Integer id);

REST implementation class:

public Response getBean(final Integer id) {
    MyBean myBean = new Service().getBean(id);
    return Response.ok(myBean).build();
}

RestClient:

IBeanResource beanResource = 
RestClientBuilder.newBuilder().baseUri(apiURI).build(IBeanResource.class);
Response beanResponse = beanResource.getBean(100);
if (beanResponse.getStatus() == Response.Status.OK.getStatusCode()) {
    MyBean bean = (MyBean) beanResponse.getEntity();
}

Error fires on line

MyBean bean = (MyBean) beanResponse.getEntity();

Has anyone seen this before? The documentation isn't great.

question from:https://stackoverflow.com/questions/65906796/microprofile-java-lang-classcastexception-sun-net-www-protocol-http-httpurlconn

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Yes that would be the expected behavior. If you inspect the value of beanResponse in debug you will see the Response is of type InboundJaxrsResonse and entity is nothing but of type HttpUrlConnector. Which is why when you try to cast it to your custom bean class it throws ClassCastException. You can try any of the following approach:

  1. you could instead do as below

    String jsonString = beanResponse.readEntity(String.class);

The above will give you the JSON response as String and then you may convert it to your respective class using libraries such as gson or jackson of your choice.

  1. In your REST WS api interface instead of returning Response return your model MyBean. As per the Microprofile rest Client spec it states the implementation of Microprofile Rest client must provide a built-in JSON-P entity provider and if it supports JSON-B then it must provide JSON-B entity provider.

microprofile-rest-client-spec-2.0


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...