Using the Invocation Builder in Java, the only options for put/post are an Entity as the object it gets it json from:
public <T> T put(final Entity<?> entity, final Class<T> responseType)
If you already have the json in a string, is there any way to put/post this without having to convert it into an Entity (which we assume is just an object)
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);
I did a quick test, and i think you error comes from you calling the object mapper directly here
Entity.json(theObjectMapper.writeValueAsString(payload))
From a quick test, if you simply pass the payload string without calling the object mapper, it seems to work
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;
}
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.