0

我得到一个 ClassCastException。我想知道我在这里做错了什么。做一个(RegistrationRequest)(element.getValue())应该有效的。我知道(RegistrationRequest)element.getValue()可能没有。

SEVERE: Servlet.service() for servlet [Jersey REST Service] in context with path [/mCruiseOnCarPool4All] threw exception
java.lang.ClassCastException: com.sun.org.apache.xerces.internal.dom.ElementNSImpl cannot be cast to com.mcruiseon.common.message.request.RegistrationRequest

服务器 Post 方法,注意方法签名中的 JAXBElement。我正在对它进行类型转换clientSession.waitAndGetResponse((RegistrationRequest)(element.getValue())) ;。这是我得到异常的行号。

@POST
@Path ("Request")
@Consumes({ MediaType.APPLICATION_JSON })
public Response post(JAXBElement<Object> element) {
    AMessageStrategy response ;
    try {
        clientSession = new ClientSession(God.mCruiseOnServer) ;
    } catch (InvalidServerDNSorIPException e) {
        e.printStackTrace();
        return Response.serverError().build() ;
    }
    sessionKey = sessionManager.setClientSession(clientSession) ;
    clientSession.setSessionKey(sessionKey) ;

    clientSession.getSendQueue().sendRequest((RegistrationRequest)(element.getValue()));                
    try {
        response = clientSession.waitAndGetResponse((RegistrationRequest)(element.getValue())) ;
    } catch (WaitedLongEnoughException e) {
        return Response.serverError().build() ;
    } catch (UnableToResolveResponseException e) {
        return Response.serverError().build() ;
    }   
    return Response.ok(response).build();
}

客户端是一个junit测试用例,相关部分代码是

ClientIdentityConcrete clientIdentity = new ClientIdentityConcrete("username", "password", "secretkey") ;
RegistrationRequest register = new RegistrationRequest(clientIdentity);
String jsonStr = mapper.writeValueAsString(clientIdentity);
HttpPost request = new HttpPost("http://localhost:8081/mCruiseOnCarPool4All/carpool4all/Registration/Request");
StringEntity se = new StringEntity(jsonStr);
se.setContentType(new BasicHeader(HTTP.CONTENT_TYPE, "application/json"));
request.setEntity(se);
HttpResponse response = client.execute(request);
4

1 回答 1

0

问题出在客户端,junit 测试用例。我没有为 with register 创建 Json 对象,而是使用 clientIdentity 创建对象。注意writeValueAsString. 我还修改了我的整个客户端以实际使用 JSON 客户端 API,而不是传统的 http。还没有工作,我得到另一个例外。但这是一个不同的问题。

ClientConfig config = new DefaultClientConfig();
        Client client = Client.create(config);
        WebResource service = client.resource(UriBuilder.fromUri(
                "http://localhost:8081/mCruiseOnCarPool4All").build());

        ClientIdentityConcrete clientIdentity = new ClientIdentityConcrete("username", "password", "secretkey");
        RegistrationRequest register = new RegistrationRequest(clientIdentity);
        AMessageStrategy response = service.path("carpool4all").path("Registration").path("Request")
                .type(MediaType.APPLICATION_JSON).post(RegistrationRequest.class, register);
        assertNotNull(response) ;
        assertNotNull(((RegistrationResponse)response).getIdentityHash()) ;
于 2012-10-22T12:07:07.843 回答