java通过http下载文件示例

代码如下所示:

import java.io.BufferedInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.RandomAccessFile;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.ProtocolException;
import java.net.URL;

public class DownloadSample {
    public static void main(String[] args) throws IOException {
        long start = System.currentTimeMillis();
        URL urlobj=new URL("http://192.168.101.51:8080/disk/storage/video.mp4");
        HttpURLConnection con= (HttpURLConnection) urlobj.openConnection();
        con.setRequestMethod("GET");
        con.setConnectTimeout(10*1000);
        con.connect();
        InputStream iis=null;
        //开始下载
        iis=new BufferedInputStream(con.getInputStream());
        RandomAccessFile raf=new RandomAccessFile("D:\\raf.mp4","rw");
        byte[] bs=new byte[1024*100];
        int length=0;
        while ((length=iis.read(bs,0,bs.length))!=-1){
            raf.write(bs,0,length);
        }
        long end = System.currentTimeMillis();
        long cast = end - start;
        System.out.println("cast="+cast + "毫秒  秒 = "+(cast/1000));
    }
}

在此做个笔记

你可能感兴趣的:(http,java,java,http,python)