java - Jersey REST 调用中的复杂查询
问题描述
我com.sun.jersey.api.*
用来调用 REST 服务,我不能使用其他库,我需要做一些更复杂的查询,比如
"customer" : {
"name": "Smith",
"documents" :
[{"id" : "100", "content" : "lorem"},
{"id" : "101", "content" : "ipsum"}]
}
这是我到目前为止尝试的代码,只是查询Customer::name
并且......它失败了。
Client client = Client.create();
WebResource resource = client.resource(URL);
String response = resource.queryParam("customer.name", "Smith")
.accept(MediaType.APPLICATION_FORM_URLENCODED)
.post(String.class);
“它失败了”我的意思是,我没有null
在服务器端而不是“Smith”接收。
编辑
好吧,我犯了明显的错误,我需要发布正文,而不是查询。仍然...
String body = "{\"customer\": {\"name\" : \"Smith\"}}";
String s = resource
.accept(MediaType.APPLICATION_FORM_URLENCODED)
.post(String.class, body);
System.out.println(body);
那打印
{“客户”:{“名称”:“史密斯”}}
对服务器的传入请求是null
.
尝试在 Postman 中使用与正文相同的 JSON - 它有效。
解决方案
我有 Post 请求的示例代码,如果您提到的 JSON 是您想要在服务器端接收的东西,请在 Post 正文中发送 JSON 而不是作为请求参数,如果它是请求参数,然后检查您是否服务器需要相同的关键参数,即 customer.name
正文中带有 JSON 数据的 Post 示例代码
public static void main(String[] args) {
try {
Client client = Client.create();
WebResource webResource = client
.resource("http://localhost:8080/RESTfulExample/rest/foo");
String input = "{
\"customer\": {
\"name\": \"Smith\",
\"documents\": [{
\"id\": \"100\",
\"content\": \"lorem\"
},
{
\"id\": \"101\",
\"content\": \"ipsum\"
}
]
}
}";
ClientResponse response = webResource.type("application/json")
.post(ClientResponse.class, input);
if (response.getStatus() != 201) {
throw new RuntimeException("Failed : HTTP error code : "
+ response.getStatus());
}
System.out.println("Output from Server .... \n");
String output = response.getEntity(String.class);
System.out.println(output);
} catch (Exception e) {
e.printStackTrace();
}
}
这是您帮助的参考链接 https://www.mkyong.com/webservices/jax-rs/restful-java-client-with-jersey-client/
编辑后 设置 webResource.type("application/json")
推荐阅读
- php - 您如何将架构与有效负载相关联?
- julia - Julia中的struct有没有repmat之类的功能?
- sql - 在 oracle 文件中添加引号
- angular - 将对象返回给服务的调用者
- javascript - 如何遍历这些数据以从中获取信息
- node.js - 使用 react 将二进制数据存储到 SQL Server
- java - Swing 中的自动刷新 (Jtable)
- r - 如何在一个箱线图中获得两个 x 轴
- python-2.7 - Amazon EMR MapReduce 流程序因错误而终止
- javascript - Debounce 功能未检测到用户何时到达页面顶部,因为它设置为在前沿与后沿触发