javaurlurlconnection

getContentLength() returning -1 but value expected was 127


What will be the output of the following Java program?

import java.net.*;
    class networking 
    {
        public static void main(String[] args) throws Exception 
        {
            URL obj = new URL("https://www.sanfoundry.com/javamcq");
            URLConnection obj1 = obj.openConnection();
            int len = obj1.getContentLength();
            System.out.print(len);
        }
    }

Note: Host URL is having length of content 127.

a) 127

b) 126

c) Runtime Error

d) Compilation Error

I found this as a question on sanfoundry as Question. 32, here is the link to it:

https://www.sanfoundry.com/java-questions-answers-freshers-experienced/

so the correct answer according to the website should be a) 127, the answer which of course I was not expecting. So, I ran the code on an IDE and got the output as -1, which is even more strange and now I am confused.

Please give me an explanation of what actually these methods do and what was wrong here.


Solution

  • -1 is returned if the server doesn't send any content length back. I've opened https://www.sanfoundry.com/javamcq in a browser and got a 404 back. I checked the network tab of the developer tools to check the headers, and the content-length header was not included.