How to stream file uploaded by user to API through Java servlet (proxy) with Apache Client

30 Views Asked by At

I need to handle a case where I need to upload a large files to third party API. User cannot upload it directly due to various reasons, so I need a proxy. For my case a classic java Servlet is the easiest way to be that proxy. So the scenario is user -> my custom servlet -> thrid party API. Due to the fact that files are large, I do not want to load them into memory, but rather stream them directly to third party API, in a way that this upload doesn't consume too much memory.

I know that I could use classic java.net API for that, something like:

        URLConnection connection = new URL("https://api.com/").openConnection();
        connection.setDoOutput(true);
        connection.setRequestProperty("Content-Type", req.getHeader("Content-Type"));
        long contentLength = req.getContentLength();
        if (contentLength > -1) {
            ((HttpURLConnection) connection).setFixedLengthStreamingMode(contentLength);
        } else {
            ((HttpURLConnection) connection).setChunkedStreamingMode(1024);
        }

        InputStream input = req.getInputStream();
        OutputStream output = connection.getOutputStream();

        for (int length; (length = input.read(buffer)) > 0;) {
            output.write(buffer, 0, length);
            output.flush();
        }
        output.close();
        connection.getInputStream();

This is fine when the API expect GET or POST requests, however my API expect PATCH request which I think is not possible to be sent with URLConnection.

And here I would need some help. I wanted to use Apache HttpClient instead of java.net, however I'm not sure if that is even possible? I couldn't find in the docs how this could be achieved. I appreciate any help or suggestions how this could be done (or maybe there is a way to send PATCH request with URLConnection?)

Cheers

0

There are 0 best solutions below