0

My backendcode i.e node.js is running fine i have checked it by sending some data in json format using postman and they are getting stored in my db(mongodb) and now i want to take the data from edittextfield android and send it to the server.the code that i have written is hitting the server but i am not getting the data. i have checked in console.log(req) it is not contaning the data that i am sending.
And i have seen previous posts that were asked related to this but it didnt helped me

here is the android code

          private static String url_create_product =   
                                   "http://192.168.1.3:3000/contactlist"; 

          protected String doInBackground(String... args) {
            String name = inputFullName.getText().toString();
            String email = inputEmail.getText().toString();
            String password = inputPassword.getText().toString();

            // Building Parameters
            List<NameValuePair> params = new ArrayList<NameValuePair>();
            params.add(new BasicNameValuePair("name", name));
            params.add(new BasicNameValuePair("email", email));
            params.add(new BasicNameValuePair("password", password));


            Log.d("params",params.toString());

            JSONObject json = jsonParser.makeHttpRequest(url_create_product,
                    "POST", params);


            Log.d("Create Response", json.toString());

            // check for success tag
            try {
                int success = json.getInt(TAG_SUCCESS);

                if (success == 1) {

                    Intent i = new Intent(getApplicationContext(), 
                     MainActivity.class);
                    startActivity(i);


                    finish();
                }
            } catch (JSONException e) {
                e.printStackTrace();
            }

            return null;

        }

here is the node.js code

       app.post('/contactlist', function (req, res) {
         console.log("i am going to insert");
        console.log(req);
        console.log(req.body);
        console.log(req.query);
        console.log(req.params);

          db.users.insert(req.body, function(err, doc) {
                                          res.json(doc);
               console.log(doc)
           });
      });

here is the error the errors that i am getting

the makehttprequest method code is public JSONObject makeHttpRequest(String url, String method, List params) {

    try {// check for request method
        if(method == "POST"){
            // request method is POST
            // defaultHttpClient
            DefaultHttpClient httpClient = new DefaultHttpClient();
            HttpPost httpPost = new HttpPost(url);
            httpPost.setEntity(new UrlEncodedFormEntity(params));
            httpPost.setHeader("Accept", "application/json");
            httpPost.setHeader("Content-type", "application/json");
            HttpResponse httpResponse = httpClient.execute(httpPost);
            HttpEntity httpEntity = httpResponse.getEntity();
            is = httpEntity.getContent();

        }else if(method == "GET"){
            // request method is GET
            DefaultHttpClient httpClient = new DefaultHttpClient();
            String paramString = URLEncodedUtils.format(params, "utf-8");
            url += "?" + paramString;
            HttpGet httpGet = new HttpGet(url);

            HttpResponse httpResponse = httpClient.execute(httpGet);
            HttpEntity httpEntity = httpResponse.getEntity();
            is = httpEntity.getContent();
        }

    } catch (UnsupportedEncodingException e) {
        e.printStackTrace();
    } catch (ClientProtocolException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }

    try {
        BufferedReader reader = new BufferedReader(new InputStreamReader(
                is, "iso-8859-1"), 8);
        StringBuilder sb = new StringBuilder();
        String line = null;
        while ((line = reader.readLine()) != null) {
            sb.append(line + "\n");
        }
        is.close();
        json = sb.toString();
    } catch (Exception e) {
        Log.e("Buffer Error", "Error converting result " + e.toString());
    }
     try {
        jObj = new JSONObject(json);
    } catch (JSONException e) {
        Log.e("JSON Parser", "Error parsing data " + e.toString());
    }

    // return JSON String
    return jObj;

}

server error

    Error: invalid json
    at parse (E:\app10 - Copy\node_modules\body-     parser\lib\types\json.js:79:15)
     at E:\app10 - Copy\node_modules\body-parser\lib\read.js:102:18
at done (E:\app10 - Copy\node_modules\body-parser\node_modules\raw-body\index.js:248:14)
at IncomingMessage.onEnd (E:\app10 - Copy\node_modules\body-parser\node_modules\raw-body\index.js:294:7)
at IncomingMessage.g (events.js:180:16)
at IncomingMessage.EventEmitter.emit (events.js:92:17)
at _stream_readable.js:920:16
at process._tickCallback (node.js:415:13)

android errors

    7292-7312/com.example.malli.login2 E/Surface﹕ getSlotFromBufferLocked: unknown buffer: 0xb9ac4360
     7292-8793/com.example.malli.login2 E/JSON Parser﹕ Error parsing data org.json.JSONException: Value Error of type java.lang.String cannot be converted to JSONObject
user3923278
  • 85
  • 1
  • 9
  • Are you setting the content type to "application/json" in your client? – Selçuk Cihan Feb 19 '16 at 09:23
  • no i have not done that – user3923278 Feb 19 '16 at 09:28
  • @SelçukCihan can u tell me code for setting content -type – user3923278 Feb 19 '16 at 09:39
  • I need to see the code for your jsonParser object, specifically the makeHttpRequest method; the content type will be set there. – Selçuk Cihan Feb 19 '16 at 09:46
  • @SelçukCihan i have added code for header in makeHttpRequest method but after this app is unfortunately getting stopped here is the code try {if(method == "POST"){ DefaultHttpClient httpClient = new DefaultHttpClient();HttpPost httpPost = new HttpPost(url); httpPost.setEntity(new UrlEncodedFormEntity(params)); httpPost.setHeader("Content-type", "application/json"); HttpResponse httpResponse = httpClient.execute(httpPost); HttpEntity httpEntity = httpResponse.getEntity(); is = httpEntity.getContent()} – user3923278 Feb 19 '16 at 10:11
  • Have you checked http://stackoverflow.com/questions/6218143/how-to-send-post-request-in-json-using-httpclient – Selçuk Cihan Feb 19 '16 at 11:46
  • @SelçukCihan yes i followed and set the headers but didnot worked – user3923278 Feb 19 '16 at 12:40
  • Could you please add the code snippet to your question, it is difficult to read it like this. You are missing `httpost.setHeader("Accept", "application/json");` try to add that too. And for the app stopping, what exception are you getting, post the details please. – Selçuk Cihan Feb 19 '16 at 13:16
  • @SelçukCihan i have added a link of image which contains the error that i am getting and added the code of makehttprequest – user3923278 Feb 19 '16 at 13:38
  • That error you posted is the end result. Your `makeHttpRequest` method is returning null and then you are trying to invoke toString() method on it. You have catched the actual exception that is the cause of your problem and you either called `e.printStackTrace` or `Log.e`. We need to see that part to figure out what is going wrong. Could you just remove all the try-catch clauses and then post the error so that we can see the root cause? – Selçuk Cihan Feb 19 '16 at 13:54
  • @SelçukCihan i have commented that part of code that was containing json.toString() and json.getInt(TAG_SUCCESS) and removed the try-catch clauses and after doing this i am getting a server error which i have mention in question itself so u can see at there. – user3923278 Feb 19 '16 at 14:12
  • @SelçukCihan and in console i am getting these error 7292-7312/com.example.malli.login2 E/Surface﹕ getSlotFromBufferLocked: unknown buffer: 0xb9ac4360 7292-8793/com.example.malli.login2 E/JSON Parser﹕ Error parsing data org.json.JSONException: Value Error of type java.lang.String cannot be converted to JSONObject – user3923278 Feb 19 '16 at 14:19
  • Try using `Map` instead of `List` like `Map params = new HashMap<>(); params.put("name", name); params.put("email", email); params.put("password", password);` – Elvis Chweya Feb 19 '16 at 14:28
  • Also, you set `httpPost.setHeader("Content-type", "application/json");` when you have clearly set `httpPost.setEntity(new UrlEncodedFormEntity(params));` which is `"Content-type", "application/x-www-form-urlencoded"`. See the conflict? – Elvis Chweya Feb 19 '16 at 14:32
  • @ElvisChweya i have changed the list to map and i have commented the UrlEncodedFormEntity part and when i have run the app it is hitting the server but i am not getting the data. req.body ,req.params , req.query all were empty – user3923278 Feb 19 '16 at 14:49
  • @SelçukCihan i am getting this error getSlotFromBufferLocked: unknown buffer: 0xb9593eb0 in android and in server side it is hitting but i am not receiving no data – user3923278 Feb 19 '16 at 15:27
  • @SelçukCihan thnks...it worked – user3923278 Feb 19 '16 at 16:31

1 Answers1

0

Try this

 JSONObject params= new JSONObject();

    try {
        params.put("name", name);     
        params.put("email", email); 
        params.put("password", password);

        HttpPost httpost = new HttpPost(url);

        httpost.setEntity(new StringEntity(params.toString()));
        httpost.setHeader("Accept", "application/json");
        httpost.setHeader("Content-type", "application/json");

        Toast.makeText(this, params.toString(), Toast.LENGTH_LONG).show();

    } catch (JSONException e) {
        e.printStackTrace();
        Toast.makeText(this, "Error", Toast.LENGTH_LONG).show();
    } 

//Other code

What is the output of console.log(req.body); on the server?

Elvis Chweya
  • 1,422
  • 9
  • 18
  • @user3923278, see the edit...I added `new StringEntity(json.toString());` to post the body as `JSON`. What the output when you log `req.body` serverside? – Elvis Chweya Feb 19 '16 at 15:34
  • now i am getting there errors Error in android converting result java.lang.NullPointerException: lock == null /com.example.malli.login2 E/JSON Parser﹕ Error parsing data org.json.JSONException: End of input at character 0 of /com.example.malli.login2 E/Surface﹕ getSlotFromBufferLocked: unknown buffer: 0xb9b7fdd0 – user3923278 Feb 19 '16 at 16:19
  • Updated to use `JSONObject` instead of `Map`, so multiple data types can be added to a `body` – Elvis Chweya Feb 19 '16 at 16:36
  • output of console.log(req.body); { email: 'qq', name: 'Qq', password: '11' } – user3923278 Feb 19 '16 at 18:00