RGabriel
RGabriel

Reputation: 3

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

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?

Upvotes: 0

Views: 1954

Answers (2)

Miguel Almeida
Miguel Almeida

Reputation: 214

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.

Upvotes: 0

Tamir Adler
Tamir Adler

Reputation: 421

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

Upvotes: 1

Related Questions