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

标签 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"}

最佳答案

您的 Java 代码需要将其 Content-Type 设置为 application/json,如下所示:

httpURLConnection.setRequestProperty("Content-Type", "application/json");

关于java - 通过 HTTP 从 android 应用程序发送到 nodejs 服务器后,我的 JSON 看起来不同,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43559960/

相关文章:

java - 如何使用 Retrofit 查询某些 JSON 项?

java - 使用 handler.obtainmessage 时出现空指针异常

node.js - Azure Bot Framework V4 (NodeJS) - LUIS 识别器返回错误?

node.js - NodeJS - 安全连接到外部 redis 服务器

javascript - 验证 Mandrill 的 X-Mandrill 签名

java - 如何将文本设置为来自另一个类的 Google map 当前位置

java - 在 Swing 中使用 Libjitsi 库处理 H264 编码的 RTP 视频流 - 如何渲染流?

java - 使用 GSON 反序列化通用容器与特定对象

java - 显示来自 getBooleanExtra 的多个字符串

android - AdMob 及其运作方式?