我在 Quarkus RestClient 上苦苦挣扎。
首先创建一个简单地打印我们的请求正文的控制器:eG
@Path("/test")
public class ExampleController {
@PUT
public void test(String data) {
System.out.println(data);
}
}
现在我们创建一个接受任何对象作为请求主体的 RestClient:
@RegisterRestClient(baseUri = "http://localhost:8081/test")
public interface RestClientExample {
@PUT
@Produces(MediaType.APPLICATION_JSON)
@Consumes(MediaType.APPLICATION_JSON)
void put(Object data);
}
请注意,我们说@Consumes(MediaType.APPLICATION_JSON)
主体应该在请求期间序列化 JSON。
做一个快速测试:
@QuarkusTest
class TestPrimitives {
@Inject
@RestClient
RestClientExample example;
@Test
void test() {
example.put("hello\nworld");
example.put(new TestRequest());
}
public static class TestRequest {
private String data = "hello\nworld";
public String getData() {
return data;
}
}
}
你会看见:
hello
world
{"data":"hello\nworld"}
如果您发送任何类型的非原始对象,则正文将被表示为 JSON。如果您发送一个字符串,则正文不是 JSON 序列化的(换行符应该\n
与第二个请求中的类似)。不幸的是,我还需要序列化的字符串。我怎样才能做到这一点?
更新
这样我可以更好地理解:将Controller替换为:所以我们进行JSON解析。
@PUT
@Consumes(MediaType.APPLICATION_JSON)
public void test(String data) {
System.out.println(Json.createReader(new StringReader(data)).readValue());
}
这将失败:
Caused by: javax.json.stream.JsonParsingException: Unexpected char 104 at (line no=1, column no=1, offset=0)
at org.glassfish.json.JsonTokenizer.unexpectedChar(JsonTokenizer.java:577)