简体   繁体   中英

Apache CXF as Client for restful API - No message body writer has been found for class

I'm using Apache CXF to consume one companies Restful API. I'm getting the following error.

Caused by: org.apache.cxf.jaxrs.client.ClientWebApplicationException: org.apache.cxf.interceptor.Fault: .No message body writer has been found for class : class org.codehaus.jettison.json.JSONObject, ContentType : application/json.

Here is my code:

public static void main(String[] args) {
        try {
            WebClient client = WebClient.create("https://aboti.securemanaged.com/rest/user");
            client.type(MediaType.APPLICATION_JSON);
            client.accept(MediaType.APPLICATION_JSON);
            JSONObject obj = new JSONObject("{\"Id\":1,\"name\":\"Alice\",\"version\":\"1.0.0\"}");
            System.out.println("Sending" + obj.toString());
            //Response responseData = client.post(obj);
            String responseData = client.post(obj, String.class);
            System.out.println("Engine one started: " + responseData);
        } catch (JSONException e) {
            e.printStackTrace();
        }

    }

But when I do curl I"m getting a valid JSON Response as follows:

curl "https://aboti.securemanaged.com/rest/user" -X POST -d '{"Id":1,"name":"Alice","version":"1.0.0"}'

{"trackingId":1564,"statusCode":"registered","status":"1"}

I tried to add a default Provider in my dispatcher servlet as follows: But am not sure how can I configure the WebClient instance to use this default provider.. or is that not the issue?

  <jaxrs:client id="serviceId" serviceClass="" address="https://aboti.securemanaged.com/rest/user">
      <jaxrs:providers>
          <bean class="org.codehaus.jackson.jaxrs.JacksonJsonProvider">
              <property name="mapper" ref="jacksonMapper" />
          </bean>
      </jaxrs:providers>
  </jaxrs:client>
  <bean id="jacksonMapper" class="org.codehaus.jackson.map.ObjectMapper"/>
  <bean id="jacksonProvider" class="org.codehaus.jackson.jaxrs.JacksonJsonProvider" />

Try this:

List<Object> providers = new ArrayList<Object>();
providers.add(new JacksonJaxbJsonProvider());

and then when you create your WebClient add the providers list as second parameter:

WebClient client = WebClient.create("https://aboti.securemanaged.com/rest/user", providers);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM