1

We have some Java services that upload files to an S3 compatible storage and generate Presigned URLs. Other Java services receive such URLs and work on the files. We need the content length of this file, without loading the whole object from the body. Is this possible? And if yes, how?

We upload via

com.amazonaws.services.s3.AmazonS3.putObject()

and create URLs with

com.amazonaws.services.s3.AmazonS3.generatePresignedUrl()

When I check the Http Headers of a file using my S3 Browser, I can see the correct Content-Length entry.

But in our services we use

OkHttpClient.newCall(
    new Builder().get()
        .url(url).build()
).execute();

And in those Response objects there is no Content-Length.

Patrick Rode
  • 120
  • 1
  • 13

1 Answers1

1

If the response is streamed (HTTP/1.1 chunked) or compressed then it won't have a content length to read from. You can probably use a HEAD request to get the headers without the body and check first.

https://stackoverflow.com/a/38673237/1542667

Yuri Schimke
  • 12,435
  • 3
  • 35
  • 69
  • I am getting a 403 error when I try a HEAD request. Also your guess seems correct - I see the protocol HTTP/1.1 in both OkHttp calls. But I also tried ` URL url = new URL("http://server.com/file.mp3"); URLConnection urlConnection = url.openConnection(); urlConnection.connect(); int file_size = urlConnection.getContentLength(); ` and this gives me the correct contentLength. I am still a bit unsure why I cannot use OkHttp3 client for this. But anyway, I can work with this. – Patrick Rode Feb 05 '21 at 07:35
  • 1
    OkHttp automatically applies compression. You could try disabling that https://stackoverflow.com/a/41165617/1542667 – Yuri Schimke Feb 05 '21 at 08:15