Search code examples
jsonhttp-error

Make JSON with complicated string acceptable to the server


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

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