mizosoft / methanol

⚗️ Lightweight HTTP extensions for Java
https://mizosoft.github.io/methanol
MIT License
239 stars 12 forks source link

Feature: Add "sized" body publisher #30

Closed gpsfl closed 3 years ago

gpsfl commented 3 years ago

Sometimes you want to provide a body publisher which can't automatically determine the size (ofInputStream for example), however you know the size of the stream through meta data or similar. For such cases it would be great to have a body publisher to which you can manually provide a content length. Something like:

public class SizedBodyPublisher implements HttpRequest.BodyPublisher {
    private final HttpRequest.BodyPublisher delegate;
    private final int length;

    public SizedBodyPublisher(HttpRequest.BodyPublisher delegate, int length) {
        this.delegate = delegate;
        this.length = length;
    }

    @Override
    public long contentLength() {
        return length;
    }

    @Override
    public void subscribe(Flow.Subscriber<? super ByteBuffer> subscriber) {
        delegate.subscribe(subscriber);
    }
}

which can be used with a method like MoreBodyHandlers.withSize(delegate, length)

mizosoft commented 3 years ago

Hi @gpsfl.

I believe this is already possible with JDK's BodyPublishers.

var sizedBodyPublisher = BodyPublishers.fromPublisher(BodyPublishers.ofInputStream(() -> null), contentLength);

Isn't this what you're suggesting?

gpsfl commented 3 years ago

Oh, you're right. The naming might be a bit counter intuitive there. Thanks a lot!