Java +apache+wget下载例子

2024-05-12 14:08
文章标签 java 下载 apache 例子 wget

本文主要是介绍Java +apache+wget下载例子,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!

使用apache调用linux的wget命令去下载文件

package com.grab.video.download;import java.io.BufferedReader;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.PrintStream;
import java.io.Writer;
import java.sql.SQLException;
import java.sql.Timestamp;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Scanner;
import java.util.regex.Matcher;
import java.util.regex.Pattern;import org.apache.commons.exec.CommandLine;
import org.apache.commons.exec.DefaultExecutor;
import org.apache.commons.exec.ExecuteException;
import org.apache.commons.exec.ExecuteWatchdog;
import org.apache.commons.lang3.StringUtils;
import org.apache.http.HttpEntity;
import org.apache.http.HttpStatus;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;import com.grab.video.controller.EncryptionUtils;
import com.grab.video.controller.SqlTaskQueue;
import com.grab.video.controller.SqlVideoList;
import com.grab.video.controller.VideoListModel;
import com.grab.video.controller.VideoStatus;/*** 根据外部命令下载视频 (独立进程程序)* 从数据库获取待下载的视频* 然后启动进程(不是线程)跑外部命令wget去把视频下载到本地服务器* 然后再去获取vid,导入polyv,更新视频状态*/
public class DownloadProcessR implements Runnable{private static String filePath = "/data/grabvideo2/";//视频文件存放的目录private static String fileUrl = "http://grab.polyv.net/video2/";//获取Vid的视频连接private static String userId="daee6f6ed7";private static int sleepTime=10*1000;public static final int SUCCESS = 0;            // 表示程序执行成功public static final String SUCCESS_MESSAGE = "程序执行成功!";public static final String ERROR_MESSAGE = "程序执行出错:";/*** 实现run方法*/public void run() {}/*** 主程序* @param args* @throws InterruptedException* @throws IOException*/public static void main(String args[]) throws InterruptedException, IOException{System.out.println("===========start==============");while(true){Thread.sleep(sleepTime);List<VideoListModel> list = new ArrayList<VideoListModel>();try {SqlVideoList svl=new SqlVideoList();//list=svl.getMiddleLaterVideo(userId);//中间往后list=svl.getWaitVideo(userId);//从后面开始(降序)System.out.println("=====待下载的视频====="+list.size());if(list.size()>0){for(int i=0;i<list.size();i++){VideoListModel vlm=list.get(i);Integer videoId=list.get(i).getId();String url=list.get(i).getUrl();String fileName=filePath+list.get(i).getTrueName();System.out.println("===========start=============="+videoId);//先获取文件大少long fileLength=0;fileLength = getFileLength(url, fileLength);try {SqlVideoList sqlVideoList = new SqlVideoList();sqlVideoList.updateFileSize(videoId,fileLength);//获取文件的大少(合计才是文件的大少,content是还有多少下载的,downloaded已下载的大少)} catch (SQLException e2) {// TODO Auto-generated catch blockSystem.out.println("获取文件大少失败");e2.printStackTrace();}if(StringUtils.isNotBlank(url)){System.out.println(i+"========"+url);String command="wget -t 3 -w 31 -c --user-agent='Polyv' "+url+" -O "+fileName;System.out.println(i+"========"+command);int exitCode = -1;try {CommandLine cmdLine = CommandLine.parse(command);DefaultExecutor executor = new DefaultExecutor();executor.setExitValue(0);ExecuteWatchdog watchdog = new ExecuteWatchdog(60*60*1000);executor.setWatchdog(watchdog);exitCode = executor.execute(cmdLine);//logger.info("combine images:"+combine + ":" + exitValue);} catch (ExecuteException e) {// TODO Auto-generated catch blocke.printStackTrace();} catch (IOException e) {// TODO Auto-generated catch blocke.printStackTrace();}//用Javajdk自带的api做,考虑的细节比较多,问题出现的概率也比较高,//Runtime runtime = Runtime.getRuntime();//Process process = runtime.exec(command);// 打印程序输出//readProcessOutput(process);// 等待程序执行结束并输出状态//int exitCode = process.waitFor();if (exitCode == SUCCESS) {System.out.println(SUCCESS_MESSAGE);File f = new File(fileName);//System.out.println(f.exists());if(f.exists()){long fileSize = f.length();System.out.println("=====File Size======="+ fileSize);//存在文件if(fileSize==fileLength){//文件大少与content-length大小相等//获取vid,更新文件下载成功状态String vid = null;// 获取vid,(根据taskId即videoId获取视频的title,cataId)if (vlm!=null) {VideoListModel video = vlm;if(StringUtils.isBlank(video.getVid())){//防止重复导入polyvString title = video.getTitle().replace(" ", "");String cataid = video.getClassifyId();String userid = video.getUserId();String trueName = video.getTrueName();long ts = System.currentTimeMillis();String sign = EncryptionUtils.md5Hex(ts + userid + "studentes");String urlmp4 = fileUrl + trueName;String pathStr="http://www.pocvo.net/uc/services/rest?method=uploadForDownloader&fileUrl="+urlmp4+"&userid="+userid+"&title="+title+"&cataid="+cataid+"&ts="+ts+"&sign="+sign;System.out.println("----url-----"+pathStr);vid=httpGetVid(pathStr);//获取vidif(vid==null){try {Thread.sleep(1000);} catch (InterruptedException e) {// TODO Auto-generated catch blocke.printStackTrace();}vid=httpGetVid(pathStr);//获取vid}//第二次if(vid==null){try {Thread.sleep(1000);} catch (InterruptedException e) {// TODO Auto-generated catch blocke.printStackTrace();}vid=httpGetVid(pathStr);//获取vid}System.out.println("------下载完成获取vid---------" + vid);}else{vid=video.getVid();System.out.println("已经有获取到vid的了"+vid);}}// 下载完成,更改视频状态为SUCCESSVideoListModel videoU = new VideoListModel();videoU.setId(videoId);videoU.setStatus(VideoStatus.SUCCESS.getValue());videoU.setVid(vid);Date date = new Date();Timestamp timeStamp = new Timestamp(date.getTime());videoU.setLastDate(timeStamp);try {SqlVideoList sqlVideoList = new SqlVideoList();sqlVideoList.updateDateVid(videoU);} catch (SQLException e) {// TODO Auto-generated catch blockSystem.out.println("下载完成,更改视频状态失败" + e);e.printStackTrace();}// 下载完成,从任务队列移除该任务try {SqlTaskQueue stq = new SqlTaskQueue();stq.deleteDate(String.valueOf(videoId));} catch (SQLException e) {// TODO Auto-generated catch blockSystem.out.println("任务移除失败" + e);e.printStackTrace();}}} else {System.err.println(ERROR_MESSAGE + exitCode);}//process.destroy();}}}}} catch (SQLException e) {// TODO Auto-generated catch blocke.printStackTrace();}}}/*** 获取文件长度* @param url* @param fileLength* @return*/private static long getFileLength(String url, long fileLength) {try {CloseableHttpClient httpclient = HttpClients.custom().setUserAgent("Polyv").setMaxConnTotal(10).setMaxConnPerRoute(10).build();HttpGet httpGet = new HttpGet(url.toString());httpGet.addHeader("User-Agent", "Polyv");//再一次设置代理CloseableHttpResponse response = httpclient.execute(httpGet);int code = response.getStatusLine().getStatusCode();// 获取状态码System.out.println("====http status===="+code);System.out.println("=====Content-Length======="+  response.getEntity().getContentLength());fileLength = response.getEntity().getContentLength();response.close();} catch (Exception e3) {// TODO Auto-generated catch blockSystem.out.println("获取文件长度失败!"+e3);e3.printStackTrace();}return fileLength;}/*** 发送请求,获取API数据*/public static String httpGetVid(String url) {String contentStr = "";String vid = null;String urlStr = url;CloseableHttpClient httpclient = HttpClients.createDefault();HttpGet httpGet = new HttpGet(urlStr);try {CloseableHttpResponse response = httpclient.execute(httpGet);InputStream is = null;Scanner sc = null;Writer os = null;if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {try {// 2、获取response的entity。HttpEntity entity = response.getEntity();is = entity.getContent();sc = new Scanner(is);while (sc.hasNext()) {contentStr = contentStr + sc.nextLine();}} catch (ClientProtocolException e) {e.printStackTrace();} finally {if (sc != null) {sc.close();}if (is != null) {is.close();}if (os != null) {os.close();}if (response != null) {response.close();}}}} catch (ClientProtocolException e) {// TODO Auto-generated catch blocke.printStackTrace();} catch (IOException e) {// TODO Auto-generated catch blocke.printStackTrace();}if (StringUtils.isNotBlank(contentStr)) {System.out.println("====="+contentStr);Pattern pattern = Pattern.compile("\"vid\":\"([0-9a-z_]{34})\"");Matcher matcher = pattern.matcher(contentStr);if(matcher.find()){vid = matcher.group(1);System.out.println(vid);}}if (vid != null) {return vid;} else {return "";}}/*** 打印进程输出* @param process 进程*/public static void readProcessOutput(final Process process) {// 将进程的正常输出在 System.out 中打印,进程的错误输出在 System.err 中打印read(process.getInputStream(), System.out);read(process.getErrorStream(), System.err);}// 读取输入流public static void read(InputStream inputStream, PrintStream out) {try {BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream));String line;while ((line = reader.readLine()) != null) {out.println(line);}} catch (IOException e) {e.printStackTrace();} finally {try {inputStream.close();} catch (IOException e) {e.printStackTrace();}}}}


这篇关于Java +apache+wget下载例子的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!



http://www.chinasem.cn/article/982831

相关文章

Java中流式并行操作parallelStream的原理和使用方法

《Java中流式并行操作parallelStream的原理和使用方法》本文详细介绍了Java中的并行流(parallelStream)的原理、正确使用方法以及在实际业务中的应用案例,并指出在使用并行流... 目录Java中流式并行操作parallelStream0. 问题的产生1. 什么是parallelS

Java中Redisson 的原理深度解析

《Java中Redisson的原理深度解析》Redisson是一个高性能的Redis客户端,它通过将Redis数据结构映射为Java对象和分布式对象,实现了在Java应用中方便地使用Redis,本文... 目录前言一、核心设计理念二、核心架构与通信层1. 基于 Netty 的异步非阻塞通信2. 编解码器三、

SpringBoot基于注解实现数据库字段回填的完整方案

《SpringBoot基于注解实现数据库字段回填的完整方案》这篇文章主要为大家详细介绍了SpringBoot如何基于注解实现数据库字段回填的相关方法,文中的示例代码讲解详细,感兴趣的小伙伴可以了解... 目录数据库表pom.XMLRelationFieldRelationFieldMapping基础的一些代

一篇文章彻底搞懂macOS如何决定java环境

《一篇文章彻底搞懂macOS如何决定java环境》MacOS作为一个功能强大的操作系统,为开发者提供了丰富的开发工具和框架,下面:本文主要介绍macOS如何决定java环境的相关资料,文中通过代码... 目录方法一:使用 which命令方法二:使用 Java_home工具(Apple 官方推荐)那问题来了,

Java HashMap的底层实现原理深度解析

《JavaHashMap的底层实现原理深度解析》HashMap基于数组+链表+红黑树结构,通过哈希算法和扩容机制优化性能,负载因子与树化阈值平衡效率,是Java开发必备的高效数据结构,本文给大家介绍... 目录一、概述:HashMap的宏观结构二、核心数据结构解析1. 数组(桶数组)2. 链表节点(Node

Java AOP面向切面编程的概念和实现方式

《JavaAOP面向切面编程的概念和实现方式》AOP是面向切面编程,通过动态代理将横切关注点(如日志、事务)与核心业务逻辑分离,提升代码复用性和可维护性,本文给大家介绍JavaAOP面向切面编程的概... 目录一、AOP 是什么?二、AOP 的核心概念与实现方式核心概念实现方式三、Spring AOP 的关

详解SpringBoot+Ehcache使用示例

《详解SpringBoot+Ehcache使用示例》本文介绍了SpringBoot中配置Ehcache、自定义get/set方式,并实际使用缓存的过程,文中通过示例代码介绍的非常详细,对大家的学习或者... 目录摘要概念内存与磁盘持久化存储:配置灵活性:编码示例引入依赖:配置ehcache.XML文件:配置

Java 虚拟线程的创建与使用深度解析

《Java虚拟线程的创建与使用深度解析》虚拟线程是Java19中以预览特性形式引入,Java21起正式发布的轻量级线程,本文给大家介绍Java虚拟线程的创建与使用,感兴趣的朋友一起看看吧... 目录一、虚拟线程简介1.1 什么是虚拟线程?1.2 为什么需要虚拟线程?二、虚拟线程与平台线程对比代码对比示例:三

Java中的.close()举例详解

《Java中的.close()举例详解》.close()方法只适用于通过window.open()打开的弹出窗口,对于浏览器的主窗口,如果没有得到用户允许是不能关闭的,:本文主要介绍Java中的.... 目录当你遇到以下三种情况时,一定要记得使用 .close():用法作用举例如何判断代码中的 input

Spring Gateway动态路由实现方案

《SpringGateway动态路由实现方案》本文主要介绍了SpringGateway动态路由实现方案,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随... 目录前沿何为路由RouteDefinitionRouteLocator工作流程动态路由实现尾巴前沿S