sasikals26
sasikals26

Reputation: 865

unable to access rest CXF with org.json.simple.JSONObject

i am trying to create a rest service and client using CXF 3.1.2 as below,

Service method declaration:

    @POST
    @Produces(MediaType.APPLICATION_JSON)
    @Consumes({"application/xml", MediaType.TEXT_PLAIN})
    @Path("/agentLogout")
    public JSONObject agentLogout(String ext) {
    JSONObject obj = new JSONObject();//org.json.simple.JSONObject
    obj.put("DN", ext);
    return obj;
    }

Client Code:

    WebClient client = WebClient.create(REST_URI); // REST_URI is configured correctly 
    client.path("agentLogout").accept(MediaType.TEXT_PLAIN);
    Response agentLogoutResponse = client.post("10245");
    System.out.println(agentLogoutResponse.readEntity(JSONObject.class));//org.json.simple.JSONObject

When i run the client code i am getting the below exception,

In Service side :

        Nov 05, 2015 3:07:08 PM org.apache.cxf.jaxrs.impl.WebApplicationExceptionMapper toResponse
    WARNING: javax.ws.rs.ClientErrorException: HTTP 406 Not Acceptable

In Client side :

    Nov 05, 2015 3:07:08 PM org.apache.cxf.jaxrs.utils.JAXRSUtils logMessageHandlerProblem
    SEVERE: No message body reader has been found for class org.json.simple.JSONObject, ContentType: */*
    Exception in thread "main" javax.ws.rs.client.ResponseProcessingException: No message body reader has been found for class org.json.simple.JSONObject, ContentType: */*

Can you please correct me here and also may i know the right way to use Json in CXF rest web service

Upvotes: 0

Views: 781

Answers (1)

Gaël J
Gaël J

Reputation: 15050

Your WS produces MediaType.APPLICATION_JSON :

@Produces(MediaType.APPLICATION_JSON)

and your client expects MediaType.TEXT_PLAIN :

client.accept(MediaType.TEXT_PLAIN);

This is the reason of "HTTP 406 Not Acceptable".

Change your client to accept JSON or you server to produce Text.


Moreover, you don't need to return a JSONObject from your methods. Just return a model object.

Returning a JSONObject will complicates things because it will return the JSON representation of the JSONObject which is not equivalent to the JSON representation of the object contained in the JSONObject.

And you could get the error "No message body reader has been found for class org.json.simple.JSONObject" because CXF doesn't know how to represent a JSONObject in JSON.

In your case you could return a Map<String,String> with one entry : key = "DN", value = "3254".

Upvotes: 1

Related Questions