Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Pass and receive JSON object from Jersey Resftul webservice from android

Scenario : Pass username and password in a json object to restful webservice and get a json object in return. Yeah, I know, Its simple but I can't get it work.

I have been trying to this from several days. So far, I have tried this:

My restful webservice code

@POST
    @Path("/testJson")
    @Consumes(MediaType.APPLICATION_JSON)
    @Produces(MediaType.APPLICATION_JSON)
    public JSONObject testJson(JSONObject inputJsonObj) throws Exception {

        JSONObject myjson = new JSONObject();

        if(inputJsonObj != null){

        System.out.println("=================================");
        System.out.println("JSON object = " + inputJsonObj.toString());
        System.out.println("=================================");

        }
        else{
            System.out.println("JSON is NULL");

        }

        myjson.put("success", "1");

        System.out.println(myjson.toString());

//        return "string returned";
        return myjson;
    }

And inside my android acivity, the code is

// POST request to <service>/SaveVehicle
        HttpPost request = new HttpPost(myURL);
        request.setHeader("Accept", "application/json");
        request.setHeader("Content-type", "application/json");
        request.setHeader("user-agent", "Yoda");


        try {
            // Build JSON string
            // JSONStringer vehicle = new JSONStringer().object()
            // .key("getItInputTO").object().key("zipCode").value("90505")
            // .key("financingOption").value("B").key("make")
            // .value("Scion").key("baseAmountFinanced").value("12000")
            // .key("modelYear").value("2010").key("trimCode")
            // .value("6221").key("totalMSRP").value("15000")
            // .key("aprRate").value("").endObject().endObject();

            JSONObject myjson = new JSONObject();
            myjson.put("1", "first");
            myjson.put("2", "second");

            StringEntity entity = new StringEntity(myjson.toString());
            entity.setContentEncoding(new BasicHeader(HTTP.CONTENT_TYPE,"application/json; charset=utf-8"));

            request.setEntity(entity);

            // Send request to WCF service
            DefaultHttpClient httpClient = new DefaultHttpClient();
            HttpContext localContext = new BasicHttpContext();
//          HttpResponse response = httpClient.execute(request, localContext);
            HttpResponse response = httpClient.execute(request);

            resCode = response.getStatusLine().getStatusCode();
            Toast.makeText(getApplicationContext(),
                    response.getStatusLine().getStatusCode() + "",
                    Toast.LENGTH_LONG).show();

            if (resCode == 200) {

                Toast.makeText(getApplicationContext(),
                        response.getStatusLine().getStatusCode() + "",
                        Toast.LENGTH_LONG).show();

                HttpEntity entity2 = (HttpEntity) response.getEntity().getContent();
                String text = getASCIIContentFromEntity(entity);

                if(text!=null){

                    JSONObject obj = new JSONObject(text);

                    lblMsg.setText("Successful!");
                }

                // BufferedReader in = new BufferedReader(new
                // InputStreamReader(response.getEntity().getContent()));
                //
                //
                // String line = "";
                // StringBuffer returnFromServer = new StringBuffer();
                //
                // while ((line = in.readLine()) != null) {
                // returnFromServer.append(line);
                // }
                // // Toast what we got from server
                // Toast.makeText(getApplicationContext(),
                // returnFromServer.toString(), Toast.LENGTH_LONG).show();
                //
                // if (entity != null) {
                // entity.consumeContent();
                // }

            }
        } catch (Exception e) {
            // TODO: handle exception
        }

The commented sections show previous tries.

Output that I get on server console

=================================
JSON object = {}
=================================
{"success":"1"}

My server side receiver json object is not getting populated i don't know why.

Note:

  1. I have INTERNET and many other permissions in my android manifest.
  2. My webservice is up and running.
  3. I have all the required jars i.e. jersey, json etc
  4. I am using Tomcat 7 for restful webservice

I would highly appreciate any help. Thanks

like image 405
Mudassir Shahzad Avatar asked Nov 27 '13 09:11

Mudassir Shahzad


People also ask

How do you get a JSON object from a RESTful web service?

First, a String URL to call the RESTful Web Service, and second, the name of the class should return with the response. So, in just one line of code, it calls the RESTful web service, parses the JSON response, and returns the Java object to you.

How do I get JSON request in Jersey?

Jersey endpoints and return a JSON responseGET /json/ , returns a JSON string. GET /json/{name} , returns an User object containg the {name} in JSON string. GET /json/all , returns a list of User objects in JSON string. POST /json/create , accepts JSON data and returns a status 201 .

Can we read JSON data directly from a Web service via HTTP?

JSON Web Services let you access portal service methods by exposing them as a JSON HTTP API. Service methods are made easily accessible using HTTP requests, both from JavaScript within the portal and from any JSON-speaking client.

How do I post JSON to a REST API endpoint in Java?

To post JSON to a REST API endpoint using Java, you must send an HTTP POST request to the REST API server and provide JSON data in the body of the Java 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.


1 Answers

I have the same problem as yours. I don't know why, but the temporary solution i am using is creating a class to handle those parameters.

That means using Jackson to convert Json Object <=> "Your Class"

See this tutorial for more information: http://www.mkyong.com/webservices/jax-rs/json-example-with-jersey-jackson/

===================================

And I just found this topic, it may be more useful than the upper solution: Jersey POST Method is receiving null values as parameters

like image 63
jean.deanny Avatar answered Sep 30 '22 22:09

jean.deanny