java - Invocation.Builder java如何将json作为字符串而不是实体发布
问题描述
使用 Java 中的 Invocation Builder,put/post 的唯一选项是一个实体作为它获取它的 json 的对象:
public <T> T put(final Entity<?> entity, final Class<T> responseType)
如果您已经在字符串中包含 json,是否有任何方法可以放置/发布它而无需将其转换为实体(我们假设它只是一个对象)
String payload = "{\"name\":\"hello\"}";
WebTarget webTarget = theHttpClient.target(url);
Invocation.Builder invocationBuilder = webTarget.request(MediaType.APPLICATION_JSON)
.header(HttpUtils.AUTHORISATION_HEADER_NAME, "Bearer " + theAccessToken);
// this outputs the string with slashes, i.e. "{\n\"name\":\"hello\"\n}"; instead of {"name":"hello"}
invocationBuilder.put( Entity.json(theObjectMapper.writeValueAsString(payload)), responseClass);
// this will not compile as payload is not an Entity
invocationBuilder.put(payload, responseClass);
解决方案
我做了一个快速测试,我认为你的错误来自你直接在这里调用对象映射器
Entity.json(theObjectMapper.writeValueAsString(payload))
通过快速测试,如果您只是传递有效负载字符串而不调用对象映射器,它似乎可以工作
pom.xml
<dependencies>
<dependency>
<groupId>org.glassfish.jersey.core</groupId>
<artifactId>jersey-client</artifactId>
<version>2.28</version>
</dependency>
<dependency>
<groupId>org.glassfish.jersey.inject</groupId>
<artifactId>jersey-hk2</artifactId>
<version>2.28</version>
</dependency>
<dependency>
<groupId>com.fasterxml.jackson.jaxrs</groupId>
<artifactId>jackson-jaxrs-json-provider</artifactId>
<version>2.8.3</version>
</dependency>
</dependencies>
testInvocationBuilder.java
public class testInvocationBuilder
{
public static void main(String[] args)
{
Client client = ClientBuilder.newClient().register(JacksonJaxbJsonProvider.class);
WebTarget webTarget = client.target("http://127.0.0.1:8000");
Invocation.Builder invocationBuilder = webTarget.request(MediaType.APPLICATION_JSON);
Payload p = new Payload();
p.name = "hello-there";
//this serializes the object in the request
Response payloadRsp = invocationBuilder.put(Entity.entity(p, MediaType.APPLICATION_JSON));
System.out.println(payloadRsp);
//this seems to pass through
String payload = "{\"name\":\"hello\"}";
Response stringRsp = invocationBuilder.put(Entity.entity(payload, MediaType.APPLICATION_JSON));
System.out.println(stringRsp);
}
public static class Payload {
public String name;
}
}
推荐阅读
- python - 将 Matplotlib Figure 转换为灰度和黑白 numpy 数组
- pine-script - 查找特定时期内的最高 MACD
- python - 需要帮助将 Windows 通知转换为 python 中的文本转语音
- java - MySql 查询动态创建的表
- c - 如何在c中将整数作为命令行参数传递?
- python - 从 CSV 转换为 Python DataFrame 中的分类数据
- python - 将新列添加到倒置二进制值的 ndarray | NumPy 数组 Python
- java - 无法构建 openfire-apns-plugin
- database - 如何通过最接近今天的数据查找记录
- c# - C#每次调用接口方法时添加自定义事件