如何在java中的Rest Post Web服务上传递json作为查询参数

问题描述 投票:0回答:2

如何在java中的Rest Post Web服务上传递json作为查询参数

例如:

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

我正在尝试这样的事情:

....

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

....

但我在运行时收到“无效的URI”。它似乎不喜欢查询参数是一个json字符串。我在某处读到了关于编码json字符串...我是否需要对json字符串进行编码?

java json rest query-parameters
2个回答
0
投票

您可以查看此问题以获取更多详细信息:Which characters make a URL invalid?

一般来说,URI中接受的字符是:[A-Z][a-z][0-9]-._~

以下字符也是允许的,但在URI的某些部分具有特殊含义::/?#[]@!$&'()*+,;=

不允许使用其他每个字符,并且必须进行百分比编码。第二组字符也应该进行百分比编码,以避免任何解析问题。

要对字符进行百分比编码,请使用其十六进制值(例如,对于space字符,十六进制值为20),并在其前面加上%字符。所以John Doe成为John%20Doe


1
投票

如果您正在使用POST请求,则应在请求正文中传递json对象,而不是在查询参数中传递。

© www.soinside.com 2019 - 2024. All rights reserved.