users@jersey.java.net

[Jersey] Re: Question on custom MessageBodyReader?

From: Markus Karg <karg_at_quipsy.de>
Date: Fri, 26 Dec 2014 10:27:10 +0100

As there are lots of questions how to program browsers (like HTML Forms, JavaScript, Flash, Applets, ...) you should first tell us which technology inside the browser you like to use.


-----Original Message-----
From: zarub2k_at_gmail.com [mailto:zarub2k_at_gmail.com]
Sent: Freitag, 26. Dezember 2014 08:06
To: users_at_jersey.java.net
Subject: [Jersey] Question on custom MessageBodyReader?

Hi All,
I have a question related with MessageBodyReader in the context of JAX-RS client API. In my scenario, I have my own custom MessageBodyReader for un-marshalling Json to Java object.

Message body reader code is as follows,

@Override
        public Book readFrom(Class<Book> clazz, Type type, Annotation[] annotations,
                MediaType mediaType, MultivaluedMap<String, String> multiValuedMap,
                InputStream stream) throws IOException, WebApplicationException {
        
                JsonReader jsonReader = Json.createReader(stream);
                JsonObject jsonObject = jsonReader.readObject();
                
                String title = jsonObject.getString("title");
                String author = jsonObject.getString("author");
                
                return new Book(title, author);
        }

BookResource code:
@POST
        @Consumes(MediaType.APPLICATION_JSON)
        @Produces(MediaType.TEXT_PLAIN)
        public String createBook(Book book) {
                System.out.println("Here book: " + book);
                return "Created successfully";
        }

REST client code:
@Test
        public void testBookJsonUnMarshaller() {
                WebTarget webTarget =
client.target("http://localhost:8080/restfullab/api").path("books");
                
                JsonObject jsonObject = Json.createObjectBuilder()
                        .add("title", "God of small things")
                        .add("author", "Roy").build();
//
//
// Form form = new Form();
// form.param("book", jsonObject.toString());
                
// Book book = new Book("God of small things", "Roy");
                
                Response response =
webTarget.request().post(Entity.entity(jsonObject.toString(),
MediaType.APPLICATION_JSON));
                System.out.println("Respose code: " + response.getStatus());
                System.out.println("Respose value: " + response.readEntity(String.class));
        }

I am able to successfully call my POST method using the above client code. The given JSON object is properly understood by the resource method.

Now my question is how to call my POST method using normal REST client (Browser client) without using the JAX-RS client code? How the JSON object can be passed along with the request? Any clue???