用http协议下载文件(HttpURLConnection)java

在安卓中,http协议经常用到,可以用来做文件的下载,断点续传,分段下载等等。

下载文件的服务器会给连接上的客户端发送文件的头数据,我们可以通过以下方法得到文件的头数据:

得到结果如下图:

null
[HTTP/1.1 200 OK]
============
X-Cache
[HIT from cache.51cdn.com]
============
Server
[nginx]
============
Access-Control-Allow-Origin
[*]
============
Connection
[keep-alive]
============
Last-Modified
[Wed, 17 Aug 2016 16:31:12 GMT]
============
Date
[Wed, 17 Aug 2016 16:49:47 GMT]
============
Via
[1.1 varnish]
============
Accept-Ranges
[bytes]
============
X-Varnish
[1148077877 1148032884]
============
X-Via
[1.1 dongdong104:6 (Cdn Cache Server V2.0), 1.1 bjdxtck20:1 (Cdn Cache Server V2.0)]
============
Cache-Control
[max-age=315360000]
============
X-Varnish-Hits
[10]
============
Expires
[Sat, 15 Aug 2026 16:49:47 GMT]
============
X-Varnish-Cache
[HIT]
============
Content-Length
[29662]
============
Age
[1]
============
Content-Type
[image/jpeg]
============

,其中有下图项,说明此文件一般可以进行断点续传(支持断点续传的文件必定有此项,有此项不一定支持断点续传)

支持断点续传的代码如下:

public class DownloadTest {
    public static void main(String[] args) {
        try {
            File file = new File("美景.jpg");
            HttpURLConnection connection = (HttpURLConnection) new URL("http://p4.so.qhmsg.com/bdr/326__/t01f1f761ee09efc574.jpg").openConnection();
            connection.setRequestMethod("GET");
            long sum = 0;
            if (file.exists()){
                sum = file.length();
                connection.setRequestProperty("Range","bytes=" + file.length() + "-");
            }

            int code = connection.getResponseCode();
            System.out.println("code = " + code);
            if (code == 200 || code == 206) {
                int contentLength = connection.getContentLength();
                System.out.println("contentLength = " + contentLength);
                InputStream is = connection.getInputStream();
                FileOutputStream fos = new FileOutputStream(file);
                byte[] buffer = new byte[102400];
                long startTime = System.currentTimeMillis();
                int length;
                while ((length = is.read(buffer)) != -1) {
                    fos.write(buffer);
                    sum = sum + length;
                    float parent = sum * 100.0f / contentLength;
                    System.out.print("\r[");
                    int p = (int)parent/2;
                    for (int i = 0; i < 50; i++) {
                        if (i < p){
                            System.out.print('=');
                        }else if (i == p){
                            System.out.print('>');
                        }else {
                            System.out.print(' ');
                        }
                    }
                    System.out.print(']');
                    System.out.printf("\t%.2f%%",parent);
                    long speed = sum * 1000/(System.currentTimeMillis() - startTime);
                    if (speed > (1 << 20)){
                        System.out.printf("\t%d MB/s", speed >> 20);
                    }else if (speed > (1 << 10)){
                        System.out.printf("\t%d KB/s", speed >> 10);
                    }else {
                        System.out.printf("\t%d B/s", speed);
                    }
                }
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

阅读更多
想对作者说点什么?

博主推荐

换一批

没有更多推荐了,返回首页