Saturday 22 April 2017

My JSON looks different after sending through HTTP from android app to nodejs server

When I'm trying to send a json as a string through HTTP to a nodejs server, there when I'm trying to log request.body it looks different and I can't acces any field.

My class that send request to server:

public class SendData extends AsyncTask<String, Void, String> {

    @Override
    protected String doInBackground(String... strings) {

        String data = "";

        HttpURLConnection httpURLConnection = null;

        try{
            httpURLConnection = (HttpURLConnection)new URL(strings[0]).openConnection();
            httpURLConnection.setRequestMethod("POST");

            httpURLConnection.setDoOutput(true);

            DataOutputStream wr = new DataOutputStream(httpURLConnection.getOutputStream());
            wr.writeBytes(strings[1]);
            wr.flush();
            wr.close();

            InputStreamReader inputStreamReader = new InputStreamReader(httpURLConnection.getInputStream());
            int inputStreamData = inputStreamReader.read();
            while (inputStreamData != -1){
                char current = (char) inputStreamData;
                inputStreamData = inputStreamReader.read();
                data += current;
            }
        } catch (Exception e){
            e.printStackTrace();
        } finally {
            if(httpURLConnection != null){
                httpURLConnection.disconnect();
            }
        }

        return data;
    }
}

The server code:

app.post('/', function (req, res) {
  var a = req.body;
  console.log(a);
  res.send(a);
})

And JSON there looks like this:

{ '{"name":"ffffc","email":"asdxx","password":"ffv","tel":"111"}': '' }

But should look like that:

{"name":"ffffc","email":"asdxx","password":"ffv","tel":"111"}


via BorČ™ Nicolae

No comments:

Post a Comment