【问题标题】:JSON data missing while sending to server发送到服务器时 JSON 数据丢失
【发布时间】:2018-01-25 11:32:47
【问题描述】:

当我解析一个 JSON 对象时,它可以很容易地以正确的格式被解析。但是,一旦我将相同的内容发送到服务器端,值就会丢失。

    JSONArray check0 = new JSONArray();
    JSONArray check1 = new JSONArray();
    JSONArray check2 = new JSONArray();

    check0.put(v11);
    check0.put(v12);
    check0.put(v13);

    check1.put(c11);
    check1.put(c12);
    check1.put(c13);

    check4.put(t11);
    check4.put(t12);
    check4.put(t13);


    draft.put("check2",id11);
    draft.put("check3",t11);

    draft.put("check0",check0);
    draft.put("check1",check1);
    draft.put("check4",check4);    

其中 v11,v12.......t12,t13 是字符串变量。

我的数据发送代码:

URL url = new URL("http://10.0.2.2:8080/initial");
HttpURLConnection connection = (HttpURLConnection)url.openConnection();
connection.setRequestMethod("POST");
connection.setRequestProperty("USER-AGENT", "Mozilla/5.0");
connection.setRequestProperty("ACCEPT-LANGUAGE", "en-US,en;0.5");
connection.setDoOutput(true);
DataOutputStream dStream = new 
DataOutputStream(connection.getOutputStream());
System.out.println(draft.toString());
dStream.writeBytes(draft.toString());

系统输出:

{"Check1":["5","4","4"],"Check0":["6","44","4"],"Check2":"17082017123406","Check4":"1228123682","Check3":["4","4","4"]}

接收post请求的代码:

app.post('/initial', function(req, res){

console.log("POST received: "+ JSON.stringify(req.body));

res.end("cool");
});

控制台输出 收到 POST:

{"{\"Check1\":":{"\"5\",\"4\",\"4\"":{"\"6\",\"44\",\"4\"":{"\"4\",\"4\",\"4\"":""}}}}

【问题讨论】:

  • 请分享您的一些代码,以便有人判断错误。
  • 我已经更新了代码,请帮帮我。
  • 请分享您创建请求 json 的代码。
  • 拜托,你能帮忙吗?

标签: java android json node.js


【解决方案1】:

尝试使用以下

con.setRequestProperty("Content-Type", "application/json; charset=UTF-8");

例子

private JSONObject uploadToServer() throws IOException, JSONException {
        String query = "https://example.com";
        String json = "{\"key\":1}";

        URL url = new URL(query);
        HttpURLConnection conn = (HttpURLConnection) url.openConnection();
        conn.setConnectTimeout(5000);
        conn.setRequestProperty("Content-Type", "application/json; charset=UTF-8");
        conn.setDoOutput(true);
        conn.setDoInput(true);
        conn.setRequestMethod("POST");

        OutputStream os = conn.getOutputStream();
        os.write(json.getBytes("UTF-8"));
        os.close();

        // read the response
        InputStream in = new BufferedInputStream(conn.getInputStream());
        String result = org.apache.commons.io.IOUtils.toString(in, "UTF-8");
        JSONObject jsonObject = new JSONObject(result);


        in.close();
        conn.disconnect();

        return jsonObject;
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2013-06-01
    • 2016-06-30
    • 1970-01-01
    • 2013-11-22
    • 1970-01-01
    • 1970-01-01
    • 2015-05-18
    • 1970-01-01
    相关资源
    最近更新 更多