java:URLConnection后台下载文件&设置代理

10 篇文章 1 订阅

前言

java后台程序URLConnection下载文件&设置代理
参考文章:让URLConnection使用代理服务器
参考文章:根据文件的url在网络上下载文件

代码

   //存储位置
    private static String sumPath = "./oosfile/";
    //读取大小
    private static int BSIZE = 1024;

    /**
     * 所需的URL等信息
     * @param map
     */
    public void czhAddData2(Map<String, String> map)  {
        //输入输出流
        FileOutputStream out = null;
        InputStream ins = null;
        try {
            //设置系统代理 不需要的省略
            Properties prop = System.getProperties();
            prop.put("http.proxyHost", "127.0.0.1");
            prop.put("http.proxyPort", "8088");
            //下载路径
            URL url = new URL(map.get("url"));
            URLConnection con = url.openConnection();
            File dir = new File(sumPath);
            if (!dir.exists()) {
                dir.mkdirs();
            }
            //文件位置
            out = new FileOutputStream(sumPath+now+".txt");
            int contentLength = con.getContentLength();
            if(contentLength>0){
                // 创建缓冲区
                byte[] buffer = new byte[BSIZE];
                ins = con.getInputStream();
                //写入
                while (ins.read(buffer) != -1) {
                    out.write(buffer);
                    out.flush();
                }
            }

        }catch (IOException e){
            throw  new RuntimeException(e);
        } finally {
            try {
                ins.close();
                out.close();
            } catch (IOException e) {
                throw  new RuntimeException(e);
            }

        }

    }

延伸

urlconnection.connect()和url.openconnection()的区别

  • 2
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值