天天看点

http协议下载文件

  1. 通过在 URL 上调用

    openConnection

    方法创建连接对象。(HttpURLConnection conn = (HttpURLConnection)new URL("网址").openConnection();)
  2. 处理设置参数和一般请求属性。(conn.

    setRequestProperty()

  3. 使用

    connect

    方法建立到远程对象的实际连接。(conn.connect())
  4. 远程对象变为可用。远程对象的头字段和内容变为可访问。(conn.

    getHeaderField(),conn.

    getInputStream等方法对连接进行操作

    )

下面是对文件下载的具体实现案例(单线程):

HttpURLConnection conn = (HttpURLConnection)new URL("资源网址").openConnection();

conn.connect();

InputStream is = connection.getInputStream();

FileOutputStream os = new FileOutputStream("保存路径");

  int count = 1024;

  if(connection.getResponseCode()==200){

  while ((count = is.read(b))!=-1) {

   os.write(b,0,count);

   }

  os.close();

  is.close();

}

多线程要设置的头文件:connection.setRequestProperty("Range", "bytes=0-4194304");

转载于:https://www.cnblogs.com/wbjgogogo/p/4949803.html