Java URLConnection : how can I find out the size of a web file?

后端 未结 6 1507
一整个雨季
一整个雨季 2020-12-04 14:32

I\'m working on a project for school, and I\'m implementing a tool which can be used to download files from the web ( with a throttling option ). The thing is, I\'m gonna ha

6条回答
  •  余生分开走
    2020-12-04 15:14

    Any HTTP response is supposed to contain a Content-Length header, so you could query the URLConnection object for this value.

    //once the connection has been opened
    List values = urlConnection.getHeaderFields().get("content-Length")
    if (values != null && !values.isEmpty()) {
    
        // getHeaderFields() returns a Map with key=(String) header 
        // name, value = List of String values for that header field. 
        // just use the first value here.
        String sLength = (String) values.get(0);
    
        if (sLength != null) {
           //parse the length into an integer...
           ...
        }
    

    It might not always be possible for a server to return an accurate Content-Length, so the value could be inaccurate, but at least you would get some usable value most of the time.

    update: Or, now that I look at the URLConnection javadoc more completely, you could just use the getContentLength() method.

提交回复
热议问题