1

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.

XylenTV
  • 53
  • 6
  • 4
    Why are you trying to put it in the URL? You're making a post request - why don't you set the content type to `text/json` and just put the JSON there? – Jon Skeet Jun 11 '15 at 08:47

1 Answers1

0

JSON should go into the request BODY. And the request content-type should by application/json.

If you want to keep using URLConnection then have a look here for example: POST request send json data java HttpUrlConnection But note it doesn't matter which library you chose for formatting the json body, it's just a text - in your case {"jsonrpc":"2.0", "id":"12345",...

There are other approaches e.g. if you use httpClient, see example 8 in the following link: http://www.programcreek.com/java-api-examples/index.php?api=org.apache.commons.httpclient.methods.StringRequestEntity

Community
  • 1
  • 1
Pelit Mamani
  • 2,321
  • 2
  • 13
  • 11