Passing JSON to WebService
You're setting the type correctly and making the request correctly.
The problem is you have nothing to handle the response.
A message body reader for Java class my.class.path.InputBean
...is basically saying, you're returning something that cannot be read, formatted, and ouputted to anything useful.
You're returning a Product type in your service, which is your octet-stream, but I don't see where you have a MessageBodyWriter to output this response to JSON.
You need:
@Provider@Produces( { MediaType.APPLICATION_JSON } )public static class ProductWriter implements MessageBodyWriter<Product>{ @Override public long getSize(Product data, Class<?> type, Type genericType, Annotation annotations[], MediaType mediaType) { // cannot predetermine this so return -1 return -1; } @Override public boolean isWriteable(Class<?> type, Type genericType, Annotation[] annotations, MediaType mediaType) { if ( mediaType.equals(MediaType.APPLICATION_JSON_TYPE) ) { return Product.class.isAssignableFrom(type); } return false; } @Override public void writeTo(Product data, Class<?> type, Type genericType, Annotation[] annotations, MediaType mediaType, MultivaluedMap<String, Object> headers, OutputStream out) throws IOException, WebApplicationException { if ( mediaType.equals(MediaType.APPLICATION_JSON_TYPE) ) { outputToJSON( data, out ); } } private void outputToJSON(Product data, OutputStream out) throws IOException { try (Writer w = new OutputStreamWriter(out, "UTF-8")) { gson.toJson( data, w ); } }}
It seems that JSONObject cannot be serialized, because no message writer could be found. Why don't you just give the InputBean as input?
Change your client code to:
public String getProduct() { Client client = Client.create(); WebResource webResource = client.resource("http://localhost:8080/product/getProduct"); InputBean data = new InputBean(1,1); // make sure there's a constructor ClientResponse response = webResource.type(MediaType.APPLICATION_JSON) .accept(MediaType.APPLICATION_JSON) .post(ClientResponse.class, data); return response.getEntity(String.class); }
Dropwizard preferes Jackson for JSON serialization & deserialization, in which case you should be able to pass InputBean directly, you can also specify the mime type manually or use the Entity wrapper, e.g.
final Client client = new JerseyClientBuilder(environment) .using(config.getJerseyClientConfiguration()) .build("jersey-client"); WebResource webResource = client.resource("http://localhost:8080/product/getProduct"); InputBean data = new InputBean(1,1); String response = webResource.post(String.class, Entity.json(data));
See http://www.dropwizard.io/1.2.2/docs/manual/client.html#jersey-client for details on how to create a configured Jersey client.