java 如何使用Jersey 2.x发送JSON请求

wbgh16ku  于 2023-05-05  发布在  Java
关注(0)|答案(2)|浏览(147)

我正在尝试使用Jersey 2.x发送休息请求。我能找到的所有样品都用Jersey 1.x。
这是在Jersey 1.X中的操作方式

String jsonPayload = "{\"name\":\"" + folderName + "\",\"description\":\"" + folderDescription + "\"}";
WebResource webResource = client.resource(restRequestUrl);
ClientResponse response =
    webResource.header("Authorization", "Basic " + encodedAuthString)
    header("Content-Type", "application/json")
    post(ClientResponse.class, jsonPayload);

我如何在Jersey 2.x中执行等效操作?

Client client = ClientBuilder.newClient(clientConfig);
WebTarget target = client.target(m_docs_base_url + "/users/items");
String jsonPayload = "{\"info\":\"" + "smith" + "\"}";
Invocation.Builder invocationBuilder = target.request("text/plain");
Response response = invocationBuilder.get(jsonPayload);
axzmvihb

axzmvihb1#

这是一个古老的问题,但对其他寻找类似东西的人来说是有益的。您的Jersey 1.x示例是一个POST请求。所以你只需要在

Response response = invocationBuilder.get(jsonPayload);

到JAX-RS 2.0

Invocation.Builder invocationBuilder =
    target.request(MediaType.APPLICATION_JSON).header("Content-Type", "application/json");

JSONObject jsonObject  = new JSONObject();
jsonObject.put("info", "smith");
Entity<?> entity = Entity.entity(jsonObject.toString(), MediaType.APPLICATION_JSON);

Response response = invocationBuilder.post(entity, Response.class);

请参阅使用JAX-RS客户端API https://eclipse-ee4j.github.io/jersey.github.io/documentation/latest/client.html的示例
Jersey 1.x到Jersey 2.x迁移指南https://eclipse-ee4j.github.io/jersey.github.io/documentation/latest/migration.html

6rqinv9w

6rqinv9w2#

你看过泽西客户的文件了吗?
https://jersey.java.net/documentation/latest/client.html#d0e4692
请记住使用post()方法和JSON有效负载,而不是像那个例子中那样使用get()方法。

相关问题