【问题标题】:how to convert list to json and pass in rest client url如何将列表转换为json并传入rest客户端url
【发布时间】:2015-09-14 12:43:50
【问题描述】:

我使用 Spring 和 Restful Web 服务实现了一个应用程序。这里我将列表转换为json格式并尝试传入客户端url,但出现以下异常:

java.lang.IllegalArgumentException: Illegal character in query at index 142: http://10.248.84.132:8082/nppWebService/updateModelGPData.do?lgdCode=33589&applicationId=8&uuid=9a26038f-6dd1-40b6-b847-f2fd16366fc0&jsonData={"noOfTrainingsOrganized":2,"noOfErsParticipated":4,"noOfOfficialsParticipated":5}
    at java.net.URI.create(Unknown Source)
    at com.sun.jersey.api.client.Client.resource(Client.java:433)
    at com.org.ep.trg.webservice.ClientRestController.main(ClientRestController.java:21)
Caused by: java.net.URISyntaxException: Illegal character in query at index 142: http://10.248.84.132:8082/nppWebService/updateModelGPData.do?lgdCode=33589&applicationId=8&uuid=9a26038f-6dd1-40b6-b847-f2fd16366fc0&jsonData={"noOfTrainingsOrganized":2,"noOfErsParticipated":4,"noOfOfficialsParticipated":5}
    at java.net.URI$Parser.fail(Unknown Source)
    at java.net.URI$Parser.checkChars(Unknown Source)
    at java.net.URI$Parser.parseHierarchical(Unknown Source)
    at java.net.URI$Parser.parse(Unknown Source)
    at java.net.URI.<init>(Unknown Source)
    ... 3 more

这是我的方法:

List<ModelGPStatusEntity>list2=new ArrayList<ModelGPStatusEntity>();
list2.add(new ModelGPStatusEntity(2,4,5));
String gson=new Gson().toJson(list2);
Client client = Client.create();
WebResource webResource = client.resource(
            "http://10.248.84.132:8082/nppWebService/updateModelGPData.do?lgdCode=33589&applicationId=8&uuid=9a26038f-6dd1-40b6-b847-f2fd16366fc0&jsonData="+gson.replace("[","").replace("]",""));

ClientResponse response = webResource.accept("application/json").get(ClientResponse.class);

if (response.getStatus() != 200) {
    throw new RuntimeException("Failed : HTTP error code : " + response.getStatus());
}

String output = response.getEntity(String.class);
System.out.println("Output from Server .... \n");
System.out.println(output);

我有两个问题:

  1. 在 url 中传递 json 数据是否正确?如果错误,传递 json 并调用客户端 url 的最佳方法是什么。

  2. 如果正确如何解决这个异常

【问题讨论】:

  • 您可以使用 POST 方法并将整个 JSON 作为字符串放入请求中
  • 您可能想要对 json 进行编码(即 { 应替换为 %7B)。另一种选择是将 json 数据的内容作为查询参数传递,或者如果您实际上正在向服务发送数据,请使用 POST 操作并将其发送到请求的有效负载中

标签: java json spring rest


【解决方案1】:

在调用 client.resource() 时,您传递的字符对于 URI 来说是非法的。特别是,未转义的双引号可能是原因。

尝试使用 UriBuilder 创建有效的 URI,并转义有问题的字符。

或者,大多数 REST Web 服务应该能够接受带有 JSON 数据的请求正文而不是 URL 的一部分的 POST。

【讨论】:

    猜你喜欢
    • 2019-05-10
    • 2019-10-22
    • 2017-03-08
    • 1970-01-01
    • 2015-04-01
    • 1970-01-01
    • 2015-05-07
    • 1970-01-01
    • 2021-01-09
    相关资源
    最近更新 更多