Question

I attempted to upload the following JSON to the server:

{
    "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/"
}

And the server returns HTTP 400.

Is there any modification I need to make to the JSON to make it acceptable to the server?

This is the code that performs the upload:

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());
        }
Was it helpful?

Solution

I solved the problem by encoding the string as a JSON string. One easy way to do that would be to use JSONObject from the json-simple API.

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());

OTHER TIPS

Your problem is that you are not escaping special characters, generating json/sql/html/etc strings like that is problematic and should be avoided.

You should consider using a json library, there are built in ones in the WCF libraries or you could use a more lightweight one such as Json.NET http://james.newtonking.com/json to achieve this.

There are a few ways to do it in Json.NET but this one would be the simplest:

var temp = new { 
    sign    = reading.getSign(),
    date    = reading.getDate(),
    month   = reading.getMonth(),
    year    = reading.getYear(),
    reading = reading.getReading()
};
string jsonString = JObject.FromObject(temp).ToString();
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top