[web-services] A message body writer for Java type, class myPackage.B, and MIME media type, application/octet-stream, was not found

I am new at RESTful webservices and was trying to update my @OneToMany relationship from a standalone client application, but I am not able to do that. I am using the Jersey implementation of JAX-RS that ships with Glassfish 3.1.1.

I have a class A that has a @OneToMany relationship with class B.

MyRestClient is my standalone client that is calling my RESTful webservice which has been deployed on Glassfish 3.1.1.

MyRestClient.java

public class MyRestClient {
    public static void main(String[] args) {    
        Client client = Client.create();        
        WebResource resource = client.resource("http://localhost:8080/myapp/rest/a/update/123");    
        B b1 = new B("debris");     
        ClientResponse response = resource.put(ClientResponse.class, b1);
        System.out.println(response.getEntity(A.class).getTitle() + " has " + response.getEntity(A.class).getBList().size() + " Bs.");
    }
}

AResource is an EJB session bean which I am using as RESTful webservice.

AResource.java

@Stateless
@Path("/a")
public class AResource {

    @EJB
    private AManager aManager;

    @PUT
    @Consumes(MediaType.APPLICATION_XML)
    @Produces(MediaType.APPLICATION_XML)
    @Path("/update/{id}")
    public Response updateA(B b, @PathParam("id") int id) {
        A a = aManager.findAById(id);
        a.addB(b);
        return Response.status(Status.OK).entity(a).build();
    }
}

When I run the client I get the following error message: com.sun.jersey.api.client.ClientHandlerException: A message body writer for Java type, class myPackage.B, and MIME media type, application/octet-stream, was not found.

Following are the domain objects in my standalone client application which is making a call to the AResource EJB session bean which I am using as the RESTful webservice.

A.java

@XmlRootElement
public class A implements Serializable{ 

    private List<B> bList = new ArrayList<B>();
    public List<B> getBList() {
        return bList;
    }
    //remaining code

}

B.java

public class B implements Serializable {

    private String text;
    private A a;    


    @XmlTransient
    public A getA() {
        return a;
    }

    public void afterUnmarshal(Unmarshaller u, Object parent) {
        this.a = (A) parent;
    }
    //remaining code

}

Could someone help me understand why this is happening and how I should solve this problem?

This question is related to web-services rest jersey java-ee-6 jax-rs

The answer is


i was facing the same problem for a get method i was returning an "int" for the @get method Strangely when i change the return type to String the error was gone.Give it a try and if someone knows the logic behind it kindly share it


You need to specify the @Provider that @Produces(MediaType.APPLICATION_XML) from B.class
An add the package of your MessageBodyWriter<B.class> to your /WEB_INF/web.xml as:

<init-param>
<param-name>com.sun.jersey.config.property.packages</param-name>
<param-value>
your.providers.package
</param-value>
</init-param>

This can also happen if you've recently upgraded Ant. I was using Ant 1.8.4 on a project, and upgraded Ant to 1.9.4, and started to get this error when building a fat jar using Ant.

The solution for me was to downgrade back to Ant 1.8.4 for the command line and Eclipse using the process detailed here


This solved my issue.

http://www.markhneedham.com/blog/2012/11/28/jersey-com-sun-jersey-api-client-clienthandlerexception-a-message-body-reader-for-java-class-and-mime-media-type-applicationjson-was-not-found/

Including following dependencies in your POM.xml and run Maven -> Update also fixed my issue.

<dependency>
    <groupId>com.sun.jersey</groupId>
    <artifactId>jersey-json</artifactId>
    <version>1.19.1</version>
</dependency>
<dependency>
   <groupId>com.owlike</groupId>
   <artifactId>genson</artifactId>
   <version>0.99</version>
</dependency>

Include this dependencies in your POM.xml and run Maven -> Update

<dependency>
    <groupId>com.sun.jersey</groupId>
    <artifactId>jersey-json</artifactId>
    <version>1.18.1</version>
</dependency>
<dependency>
   <groupId>com.owlike</groupId>
   <artifactId>genson</artifactId>
   <version>0.99</version>
</dependency>

Adding reference to:

<dependency>
    <groupId>com.sun.jersey</groupId>
    <artifactId>jersey-json</artifactId>
    <version>${jersey1.version}</version>
</dependency>

As long as adding clientConfig.getFeatures().put(JSONConfiguration.FEATURE_POJO_MAPPING, true); on client creation solved the issue for me:

ClientConfig clientConfig = new DefaultClientConfig();
clientConfig.getFeatures().put(JSONConfiguration.FEATURE_POJO_MAPPING, true);
Client client = Client.create(clientConfig);

Make sure that all these libs are in your class path:

compile(group: 'com.sun.jersey', name: 'jersey-core',        version: '1.19.4') 
compile(group: 'com.sun.jersey', name: 'jersey-server',      version: '1.19.4') 
compile(group: 'com.sun.jersey', name: 'jersey-servlet',     version: '1.19.4')
compile(group: 'com.sun.jersey', name: 'jersey-json',        version: '1.19.4')
compile(group: 'com.sun.jersey', name: 'jersey-client',      version: '1.19.4')
compile(group: 'javax.ws.rs', name: 'jsr311-api', version: '1.1.1')
compile(group: 'org.codehaus.jackson', name: 'jackson-core-asl', version: '1.9.2')
compile(group: 'org.codehaus.jackson', name: 'jackson-mapper-asl', version: '1.9.2')
compile(group: 'org.codehaus.jackson', name: 'jackson-core-asl',   version: '1.9.2')
compile(group: 'org.codehaus.jackson', name: 'jackson-jaxrs',      version: '1.9.2')
compile(group: 'org.codehaus.jackson', name: 'jackson-xc',         version: '1.9.2')

Add "Pojo Mapping" and "Jackson Provider" to the jersey client config:

ClientConfig clientConfig = new DefaultClientConfig();
clientConfig.getFeatures().put(JSONConfiguration.FEATURE_POJO_MAPPING, Boolean.TRUE);
clientConfig.getClasses().add(JacksonJsonProvider.class);

This solve to me!

ClientResponse response = null;

response = webResource
        .type(MediaType.APPLICATION_JSON)
        .accept(MediaType.APPLICATION_JSON)
        .get(ClientResponse.class);


if (response.getStatus() == Response.Status.OK.getStatusCode()) {

    MyClass myclass = response.getEntity(MyClass.class);
    System.out.println(myclass);
}

This also happens if you're missing an empty public constructor for the Entity (could be for JSON, XML etc)..


You have to do two things to remove this error.

  1. The @xmlElement mapping in the model
  2. The client side:

    response = resource.type(MediaType.APPLICATION_XML).put(ClientResponse.class, b1); //consume

    or

    response = resource.accept(MediaType.APPLICATION_XML).put(ClientResponse.class, b1); //produce


Examples related to web-services

How do I POST XML data to a webservice with Postman? How to send json data in POST request using C# org.springframework.web.client.HttpClientErrorException: 400 Bad Request How to call a REST web service API from JavaScript? The request was rejected because no multipart boundary was found in springboot Generating Request/Response XML from a WSDL How to send a POST request using volley with string body? How to send post request to the below post method using postman rest client How to pass a JSON array as a parameter in URL Postman Chrome: What is the difference between form-data, x-www-form-urlencoded and raw

Examples related to rest

Access blocked by CORS policy: Response to preflight request doesn't pass access control check Returning data from Axios API Access Control Origin Header error using Axios in React Web throwing error in Chrome JSON parse error: Can not construct instance of java.time.LocalDate: no String-argument constructor/factory method to deserialize from String value How to send json data in POST request using C# How to enable CORS in ASP.net Core WebAPI RestClientException: Could not extract response. no suitable HttpMessageConverter found REST API - Use the "Accept: application/json" HTTP Header 'Field required a bean of type that could not be found.' error spring restful API using mongodb MultipartException: Current request is not a multipart request

Examples related to jersey

How to download a file using a Java REST service and a data stream File upload along with other object in Jersey restful web service MessageBodyWriter not found for media type=application/json org.glassfish.jersey.servlet.ServletContainer ClassNotFoundException How to add Headers on RESTful call using Jersey Client API java.lang.ClassNotFoundException: com.sun.jersey.spi.container.servlet.ServletContainer Dependency injection with Jersey 2.0 How to send and receive JSON data from a restful webservice using Jersey API Jersey client: How to add a list as query parameter @POST in RESTful web service

Examples related to java-ee-6

A message body writer for Java type, class myPackage.B, and MIME media type, application/octet-stream, was not found What is javax.inject.Named annotation supposed to be used for?

Examples related to jax-rs

Java 8 LocalDate Jackson format File upload along with other object in Jersey restful web service Best practice for REST token-based authentication with JAX-RS and Jersey MessageBodyWriter not found for media type=application/json Can not deserialize instance of java.util.ArrayList out of START_OBJECT token Read response body in JAX-RS client from a post request What is the difference between JAX-RS and JAX-WS? javax.xml.bind.JAXBException: Class *** nor any of its super class is known to this context When to use @QueryParam vs @PathParam How to set up JAX-RS Application using annotations only (no web.xml)?