Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to send and receive JSON data from a restful webservice using Jersey API

Tags:

java

json

jersey

@Path("/hello")
public class Hello {

    @POST
    @Path("{id}")
    @Produces(MediaType.APPLICATION_JSON)
    @Consumes(MediaType.APPLICATION_JSON)
    public JSONObject sayPlainTextHello(@PathParam("id")JSONObject inputJsonObj) {

        String input = (String) inputJsonObj.get("input");
        String output="The input you sent is :"+input;
        JSONObject outputJsonObj = new JSONObject();
        outputJsonObj.put("output", output);

        return outputJsonObj;
    }
} 

This is my webservice (I am using Jersey API). But I could not figure out a way to call this method from a java rest client to send and receive the json data. I tried the following way to write the client

ClientConfig config = new DefaultClientConfig();
Client client = Client.create(config);
WebResource service = client.resource(getBaseURI());
JSONObject inputJsonObj = new JSONObject();
inputJsonObj.put("input", "Value");
System.out.println(service.path("rest").path("hello").accept(MediaType.APPLICATION_JSON).entity(inputJsonObj).post(JSONObject.class,JSONObject.class));

But this shows the following error

Exception in thread "main" com.sun.jersey.api.client.ClientHandlerException: com.sun.jersey.api.client.ClientHandlerException: A message body writer for Java type, class java.lang.Class, and MIME media type, application/octet-stream, was not found
like image 605
Ayan Biswas Avatar asked Jan 30 '13 09:01

Ayan Biswas


People also ask

How do I get JSON request in Jersey?

if you want your json as an Vote object then simple use @RequestBody Vote body in your mathod argument , Spring will automatically convert your Json in Vote Object.

How does REST API send JSON data?

To post JSON to a REST API endpoint, you must send an HTTP POST request to the REST API server and provide JSON data in the body of the POST message. You also need to specify the data type in the body of the POST message using the Content-Type: application/json request header.

Can we send JSON object in GET request in REST API?

To answer your question, yes you may pass JSON in the URI as part of a GET request (provided you URL-encode).


2 Answers

Your use of @PathParam is incorrect. It does not follow these requirements as documented in the javadoc here. I believe you just want to POST the JSON entity. You can fix this in your resource method to accept JSON entity.

@Path("/hello")
public class Hello {

  @POST
  @Produces(MediaType.APPLICATION_JSON)
  @Consumes(MediaType.APPLICATION_JSON)
  public JSONObject sayPlainTextHello(JSONObject inputJsonObj) throws Exception {

    String input = (String) inputJsonObj.get("input");
    String output = "The input you sent is :" + input;
    JSONObject outputJsonObj = new JSONObject();
    outputJsonObj.put("output", output);

    return outputJsonObj;
  }
}

And, your client code should look like this:

  ClientConfig config = new DefaultClientConfig();
  Client client = Client.create(config);
  client.addFilter(new LoggingFilter());
  WebResource service = client.resource(getBaseURI());
  JSONObject inputJsonObj = new JSONObject();
  inputJsonObj.put("input", "Value");
  System.out.println(service.path("rest").path("hello").accept(MediaType.APPLICATION_JSON).post(JSONObject.class, inputJsonObj));
like image 153
Arul Dhesiaseelan Avatar answered Oct 07 '22 00:10

Arul Dhesiaseelan


For me, parameter (JSONObject inputJsonObj) was not working. I am using jersey 2.* Hence I feel this is the

java(Jax-rs) and Angular way

I hope it's helpful to someone using JAVA Rest and AngularJS like me.
@POST
@Consumes(MediaType.TEXT_PLAIN)
@Produces(MediaType.APPLICATION_JSON)
public Map<String, String> methodName(String data) throws Exception {
    JSONObject recoData = new JSONObject(data);
    //Do whatever with json object
}

Client side I used AngularJS

factory.update = function () {
data = {user:'Shreedhar Bhat',address:[{houseNo:105},{city:'Bengaluru'}]};
        data= JSON.stringify(data);//Convert object to string
        var d = $q.defer();
        $http({
            method: 'POST',
            url: 'REST/webApp/update',
            headers: {'Content-Type': 'text/plain'},
            data:data
        })
        .success(function (response) {
            d.resolve(response);
        })
        .error(function (response) {
            d.reject(response);
        });

        return d.promise;
    };
like image 40
shreedhar bhat Avatar answered Oct 07 '22 01:10

shreedhar bhat