0

How do I pass json as a query parameter on Rest Post web service in java

For example:

https://testvpa.net/WebService/ViALoggingRestWS/ViALoggingService.svc/StartCall?parameter={"machineName":"KK-IVR01","appName":"KKApp","startTime":"2018-02-06T21:38:32","portID":"01","ani":"9189280000","dnis":"8559281111","ctiCallID":"01"}

I am trying something like this:

....

try{
    JSONObject obj = new JSONObject();
    obj.put("machineName",machineName);
    obj.put("appName", appName);
    obj.put("startTime", formattedCurrentDate);
    obj.put("portID",portID);
    obj.put("ani",ani);
    obj.put("dnis", dnis);
    obj.put("ctiCallID", ctiCallID);

    String strobj = obj.toString();

    String uri = wsUri+"/StartCall?";

    HttpClient client = new HttpClient();
    client.getParams().setConnectionManagerTimeout(1300);
    client.getParams().setSoTimeout(13000);

    PostMethod method = new PostMethod(uri);
    method.addRequestHeader("Content-Type", "application/x-www-form-urlencoded");
    method.setQueryString("parameter="+strobj );

    int statusCode = client.executeMethod(method);

    byte[] responseBody = method.getResponseBody();
    output = new String(responseBody);
}

....

But I am getting an "Invalid URI" at runtime. It doesn't seem to like the query parameter being a json string. I read somewhere about encoding the json string ... Do I somehow need to encode the json string?

Rohan Pillai
  • 917
  • 3
  • 17
  • 26
RGabriel
  • 3
  • 2

2 Answers2

1

If you are using POST request, you should pass the json object in the body of the request and not in the query params.

Tamir Adler
  • 341
  • 2
  • 14
  • You should add how OP would do this. Else this is not really more than a comment, I am afraid. – geisterfurz007 Feb 28 '18 at 18:46
  • please refer to this question - https://stackoverflow.com/questions/2092474/postmethod-setrequestbodystring-deprecated-why – Tamir Adler Feb 28 '18 at 19:05
  • Unfortunately, the vendor supplying this web service says it has to be consumed this way. It wont work putting the json in the body, has to be a query parameter. – RGabriel Feb 28 '18 at 22:16
0

You can check this question for more details: Which characters make a URL invalid?

Generally speaking, the accepted characters in a URI are: [A-Z][a-z][0-9]-._~

The following characters are also allowed, but have special meaning in some parts of the URI: :/?#[]@!$&'()*+,;=

Every other character is not allowed and must be percent-encoded. The second set of characters should also be percent-encoded to avoid any parsing problems.

To percent encode a character you take its hex value (e.g. for the space character the hex value is 20) and prefix it with the % character. So John Doe becomes John%20Doe.

Miguel Almeida
  • 204
  • 1
  • 4
  • 15