Nested JSON in URL request with Java

I’m attempting to nest JSON objects in the URL of a HTTP request to make use of an API. The raw JSON is

{
    "jsonrpc":"2.0",
    "id":"12345",
    "params":{
        "api_key": "e983322o",
        "preset_id": "12345678",
        "user_id": "3265999"
    },
    "method":"Tags.get"
}

(This is tested and works in a REST client)

And the method in Java is

private static void printSiteTags() {
    try {
        List<NameValuePair> params = new LinkedList<>();
        params.add(new BasicNameValuePair("jsonrpc", "2.0"));
        params.add(new BasicNameValuePair("id", "12345"));

        params.add(new BasicNameValuePair("params[0]", new BasicNameValuePair("api_key", API_KEY).toString()));
        params.add(new BasicNameValuePair("params[1]", new BasicNameValuePair("preset_id", "12345678").toString()));
        params.add(new BasicNameValuePair("params[2]", new BasicNameValuePair("user_id", "3265999").toString()));

        params.add(new BasicNameValuePair("method", "Tags.get"));

        String rawUrl = addToUrl(SITE_URL, params);
        //addToUrl just uses URLEncodedUtils
        System.out.println(rawUrl);
        URL url = new URL(rawUrl);

        HttpURLConnection conn = (HttpURLConnection)url.openConnection();
        conn.setRequestMethod("POST");
        conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
        conn.setDoOutput(true);

        Reader in = new BufferedReader(new InputStreamReader(conn.getInputStream(), "UTF-8"));
        for ( int c = in.read(); c != -1; c = in.read() )
            System.out.print((char)c);

    } catch (IOException e) {
        e.printStackTrace();
    }
}

The result of the raw URL is

[base site]?jsonrpc=2.0&id=12345&%5Bparams%5D%5Bapi_key%5D=e983322o&params%5B1%5D=preset_id%3D12345678&params%5B2%5D=user_id%3D3265999&method=Tags.get

(Which is obviously wrong)

Evidently, the response from the server is an error.


Source: json

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.