HTTP 单线程 模拟迅雷下载

本文介绍了一个使用Java实现的HTTP下载示例,展示了如何通过HttpURLConnection发起GET请求来下载文件,并实时显示下载进度。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

HTTP:超文本传输协议
      功能:HTTP是客户端浏览器或其他程序与Web服务器之间的应用层通信协议
      SP:空格
      CRLF:换行
      
    URI:包含UTL   统一资源标识符  /index.html
    URL:统一资源定位符  http://www.baidu.com:80/index.html
    URN:统一资源名   比如QQ邮箱
    URI=URL+URN
    

    请求的报头:请求的环境


实例:

package com.yc.net.http01;

import java.io.BufferedOutputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.text.NumberFormat;

public class XueLei01 {
    public static void main(String[] args) {
        try {
            URL url=new URL("http://dlsw.baidu.com/sw-search-sp/soft/ca/13442/Thunder_dl_7.9.41.5020_setup.1444900082.exe");
            HttpURLConnection con=(HttpURLConnection) url.openConnection();//获得连接对象
        //    con.setRequestMethod("HEAD");   //设置请求方式   head get post.....
            con.setRequestMethod("GET");
            con.connect();//建立连接
            int responseCode=con.getResponseCode();//获取响应
            if(responseCode==200){
                System.out.println("连接成功");
                
                long totalSize=con.getContentLengthLong();// 文件总长度
                long downloadSize=0;//下载的长度
                //保存到本地磁盘的字节输出缓存流
                BufferedOutputStream out=new BufferedOutputStream(new FileOutputStream("d:\\Thunder.exe"));
                InputStream in=con.getInputStream();//获得响应的实体内容             单线程下载
                
                
                byte[] bs=new byte[1024*1024];   //以M为单位下载
                int length=0;
                while((length=in.read(bs))!=-1){
                    
                    out.write(bs,0,length);//写入到文件
                    downloadSize+=length;//累加下载长度
                    
                    System.out.println("下载长度为"+(downloadSize *100.0/totalSize)+"%");
                    
                }
                out.flush();
                out.close();
                in.close();
                System.out.println("下载成功");
                
            }else{
                System.out.println(con.getResponseMessage());//获得响应码   获得响应信息
            }
        } catch (MalformedURLException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

wen's

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值