通过HTTP从Android应用程序发送到nodejs服务器后,我的JSON看起来有所不同

时间:2017-04-22 13:43:03

标签: java android node.js http

当我尝试通过HTTP将json作为字符串发送到nodejs服务器时,当我尝试记录request.body时,它看起来不同,我无法访问任何字段。

我的向服务器发送请求的类:

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;
    }
}

服务器代码:

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

JSON看起来像这样:

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

但应该是这样的:

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

1 个答案:

答案 0 :(得分:1)

您的Java代码需要将其内容类型设置为inspect element,如下所示:

View Source