2

我在 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)
4

1 回答 1

0

不幸的是,您告诉其余客户端发送 JSON,而 String 是有效的 JSON 对象,因此您的结果是合乎逻辑的。

当您使用 System.out 记录字符串时,该\n字符显示为换行符。

对我来说,这段代码没有任何问题,它可以正常工作。

如果您希望您\n不被评估为换行符,则需要\从您的呼叫站点转义(其余客户端代码可以)

@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;
        }
    }
}
于 2020-11-30T12:01:52.747 回答