0

我尝试将以下 JSON 上传到服务器:

{
    "sign": "cancer",
    "date": 30,
    "month": 10,
    "year": 2013,
    "reading": "vQdKU0SufpGmvkkyfvkdUr&yg/ rodatmifvkyfav ay:avjzpfrnf/ olwpfyg; rodapvkdaom udpörsm;udk rvkyfavaumif;avjzpfrnf/ vltrsm; olwpfyg;\ pdwf0ifpm;p&m jzpfaewufonf/ aiGaMu;udpö owdxm;NyD; udkifwG,fyg/ vuf0,faiGaysufaomaMumifh Mum;pdkufavsmf&udef; MuHKrnf/"
}

服务器返回 HTTP 400。

我需要对 JSON 进行任何修改以使其被服务器接受吗?

这是执行上传的代码:

HttpURLConnection conn = (HttpURLConnection) url.openConnection();
        conn.setDoOutput(true);
        conn.setRequestMethod("POST");
        conn.setRequestProperty("Content-Type", "application/json");
        conn.setRequestProperty("Accept", "application/json");

        String input = "{\"sign\": \"" + reading.getSign() + "\"" + ", \"date\": " 
                + reading.getDate() + ", \"month\": " + reading.getMonth() 
                + ", \"year\": " + reading.getYear()
                + ", \"reading\": \"" + reading.getReading() + "\"}";

        OutputStream os = conn.getOutputStream();
        os.write(input.getBytes());
        os.flush();                        

        if (conn.getResponseCode() != HttpURLConnection.HTTP_OK) {
            throw new RuntimeException("Failed : HTTP error code : "
                    + conn.getResponseCode());
        }
4

2 回答 2

1

我通过将字符串编码为 JSON 字符串解决了这个问题。一种简单的方法是使用 json-simple API 中的 JSONObject。

JSONObject inputJson = new JSONObject();
        inputJson.put("sign", reading.getSign());
        inputJson.put("date", reading.getDate());
        inputJson.put("month", reading.getMonth());
        inputJson.put("year", reading.getYear());
        inputJson.put("reading", reading.getReading());
于 2013-10-31T05:24:10.323 回答
1

你的问题是你没有转义特殊字符,生成像这样的 json/sql/html/etc 字符串是有问题的,应该避免。

您应该考虑使用 json 库,WCF 库中有内置的库,或者您可以使用更轻量级的库,例如 Json.NET http://james.newtonking.com/json来实现这一点。

在 Json.NET 中有几种方法可以做到这一点,但这是最简单的一种:

var temp = new { 
    sign    = reading.getSign(),
    date    = reading.getDate(),
    month   = reading.getMonth(),
    year    = reading.getYear(),
    reading = reading.getReading()
};
string jsonString = JObject.FromObject(temp).ToString();
于 2013-10-31T05:33:39.233 回答