小编Cha*_*lle的帖子

如何为 Java 11 HttpRequest 创建自定义 BodyPublisher

我正在尝试创建一个自定义BodyPublisher来反序列化我的 JSON 对象。我可以在创建请求时反序列化 JSON 并使用 的ofByteArray方法,BodyPublishers但我宁愿使用自定义发布者。

public class CustomPublisher implements HttpRequest.BodyPublisher {
    private byte[] bytes;
    
    public CustomPublisher(ObjectNode jsonData) {
        ...
        // Deserialize jsonData to bytes
        ...
    }
    
    @Override
    public long contentLength() {
        if(bytes == null) return 0;
        return bytes.length
    }
    
    @Override
    public void subscribe(Flow.Subscriber<? super ByteBuffer> subscriber) {
        CustomSubscription subscription = new CustomSubscription(subscriber, bytes);
        subscriber.onSubscribe(subscription);       
    }

    private CustomSubscription implements Flow.Subscription {
         private final Flow.Subscriber<? super ByteBuffer> subscriber;
         private boolean cancelled;
         private Iterator<Byte> byterator;

         private …
Run Code Online (Sandbox Code Playgroud)

java java-http-client java-11

5
推荐指数
1
解决办法
884
查看次数

标签 统计

java ×1

java-11 ×1

java-http-client ×1