Java自学者论坛

 找回密码
 立即注册

手机号码,快捷登录

恭喜Java自学者论坛(https://www.javazxz.com)已经为数万Java学习者服务超过8年了!积累会员资料超过10000G+
成为本站VIP会员,下载本站10000G+会员资源,会员资料板块,购买链接:点击进入购买VIP会员

JAVA高级面试进阶训练营视频教程

Java架构师系统进阶VIP课程

分布式高可用全栈开发微服务教程Go语言视频零基础入门到精通Java架构师3期(课件+源码)
Java开发全终端实战租房项目视频教程SpringBoot2.X入门到高级使用教程大数据培训第六期全套视频教程深度学习(CNN RNN GAN)算法原理Java亿级流量电商系统视频教程
互联网架构师视频教程年薪50万Spark2.0从入门到精通年薪50万!人工智能学习路线教程年薪50万大数据入门到精通学习路线年薪50万机器学习入门到精通教程
仿小米商城类app和小程序视频教程深度学习数据分析基础到实战最新黑马javaEE2.1就业课程从 0到JVM实战高手教程MySQL入门到精通教程
查看: 421|回复: 0

Java下载文件 爬虫 超时处理解决方案

[复制链接]
  • TA的每日心情
    奋斗
    5 小时前
  • 签到天数: 758 天

    [LV.10]以坛为家III

    2034

    主题

    2092

    帖子

    70万

    积分

    管理员

    Rank: 9Rank: 9Rank: 9

    积分
    708222
    发表于 2021-7-17 20:01:50 | 显示全部楼层 |阅读模式
    import java.util.List;
    import java.io.BufferedReader;
    import java.io.BufferedWriter;
    import java.io.File;
    import java.io.FileNotFoundException;
    import java.io.FileOutputStream;
    import java.io.FileReader;
    import java.io.FileWriter;
    import java.io.IOException;
    import java.io.InputStream;
    import java.io.InputStreamReader;
    import java.io.OutputStream;
    import java.net.HttpURLConnection;
    import java.net.MalformedURLException;
    import java.net.SocketTimeoutException;
    import java.net.URL;
    import java.util.ArrayList;
    import java.util.logging.Logger;
    import java.util.regex.Matcher;
    import java.util.regex.Pattern;
    
    public class Main {
    
     public static final int sleepMsPerConnection = 1000;
     public static final int timeOutMs = 20000;
     public static final int retry = 2;
    
     private static void download(String urlStr, String filePath) {
      int retryCount = 0;
      while(true){
       try {
        DownloadThread thread = new DownloadThread(urlStr, filePath);
        thread.start();
        thread.join(timeOutMs);
        if(!thread.isAlive()){
         return;
        }else{
         thread.interrupt();//实测并不能结束线程,请参考如何中断JAVA线程一文
        }
       } catch (InterruptedException e) {
        e.printStackTrace();
       }
       retryCount++;
       if(retryCount > retry){
        throw new RuntimeException("still timeout after retry " + (retry - 1) + " times");
       }
       System.out.println("retry");
      }
     }
    
    
     private static String getHtml(String urlStr) {
      int retryCount = 0;
      while(true){
       try {
        GetHtmlThread thread = new GetHtmlThread(urlStr);
        thread.start();
        thread.join(timeOutMs);
        if(!thread.isAlive()){
         return thread.html;
        }else{
         thread.interrupt();
        }
       } catch (InterruptedException e) {
        e.printStackTrace();
       }
       retryCount++;
       if(retryCount > retry){
        throw new RuntimeException("still timeout after retry " + (retry - 1) + " times");
       }
       System.out.println("retry");
      }
     }
    }
    
    import java.io.BufferedReader;
    import java.io.InputStreamReader;
    import java.net.URL;
    
    public class GetHtmlThread extends Thread {
    
     public String html;
     private String urlStr;
    
     public GetHtmlThread(String urlStr) {
      this.urlStr = urlStr;
     }
    
     public void run() {
      try {
       Thread.sleep(Main.sleepMsPerConnection);
       URL url = new URL(urlStr);
       StringBuilder sb = new StringBuilder();
       BufferedReader br = new BufferedReader(new InputStreamReader(url
         .openStream()));
       String line = null;
       while ((line = br.readLine()) != null) {
        sb.append(line);
        sb.append('\n');
       }
       br.close();
       this.html = sb.toString();
      } catch (InterruptedException e) {
       // do nothing?
      } catch (Exception e) {
       e.printStackTrace();
       System.exit(1);
      }
     }
    }
    
    import java.io.File;
    import java.io.FileOutputStream;
    import java.io.IOException;
    import java.io.InputStream;
    import java.io.OutputStream;
    import java.net.URL;
    
    public class DownloadThread extends Thread {
    
     private String urlStr;
     private String filePath;
    
     public DownloadThread(String urlStr, String filePath) {
      this.urlStr = urlStr;
      this.filePath = filePath;
     }
    
     public void run() {
      try {
       URL url = new URL(urlStr);
       InputStream is = url.openStream();
       File pdfFile = new File(filePath);
       FileOutputStream os = new FileOutputStream(pdfFile);
       copyStream(is, os);
       is.close();
       os.close();
      } catch (Exception e) {
       e.printStackTrace();
       System.exit(1);
      }
     }
     
     /**
      * still need to close inputstream and outputstream after call this method
      * @param inputStream
      * @param outputStream
      * @throws IOException
      */
     private void copyStream(InputStream inputStream, OutputStream outputStream)
       throws IOException {
      byte[] b = new byte[1024];
      int len;
      while ((len = inputStream.read(b)) > 0) {
       outputStream.write(b, 0, len);
      }
      outputStream.flush();
     }
    }
    哎...今天够累的,签到来了1...
    回复

    使用道具 举报

    您需要登录后才可以回帖 登录 | 立即注册

    本版积分规则

    QQ|手机版|小黑屋|Java自学者论坛 ( 声明:本站文章及资料整理自互联网,用于Java自学者交流学习使用,对资料版权不负任何法律责任,若有侵权请及时联系客服屏蔽删除 )

    GMT+8, 2024-7-7 21:35 , Processed in 0.053996 second(s), 27 queries .

    Powered by Discuz! X3.4

    Copyright © 2001-2021, Tencent Cloud.

    快速回复 返回顶部 返回列表