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

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

我正在尝试使用 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);
java json jersey reset
2个回答
0
投票

这是一个老问题,但为了其他寻找类似问题的人的利益。 您的 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


-3
投票

你看过 Jersey 客户端文档了吗?

https://jersey.java.net/documentation/latest/client.html#d0e4692

请记住对您的 JSON 有效负载使用 post() 方法,而不是像该示例中那样使用 get() 方法。

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