视频、音频、图片代理下载

视频、音频、图片代理下载


视频、音频、图片代理下载





  /**
     * 音频下载
     */
    @RequestMapping("/audio/download")
    public void downloadFile(HttpServletRequest request, HttpServletResponse response) throws IOException {  
        //String id = request.getParameter("id"); 
        String filePath = ServletRequestUtils.getStringParameter(request, "filePath", ""); //
        String fileName = ServletRequestUtils.getStringParameter(request, "fileName", ""); //
        String destUrl = filePath;
        //LOG.info("--------------"+filePath); 
        
        String fileFormat=filePath.substring(filePath.lastIndexOf("."));
        String name="";
        if(StringUtils.isBlank(fileName)){
            name=new SimpleDateFormat("yyyyMMddHHmmss").format(new Date())+fileFormat;
        }else {
            name=fileName.trim()+fileFormat;
        }
        //File f = new File(filePath);
        //response.setHeader("Content-Disposition", "attachment; filename="+java.net.URLEncoder.encode(f.getName(),"UTF-8"));  
        //LOG.info("--------------"+f.getName());

        // 建立链接  
        URL url = new URL(destUrl);  
        HttpURLConnection httpUrl = (HttpURLConnection) url.openConnection();  
        // 连接指定的资源  
        httpUrl.connect();  
        // 获取网络输入流  
        BufferedInputStream bis = new BufferedInputStream(httpUrl.getInputStream());  
  
        Integer lenf=httpUrl.getContentLength();
        //String lenf=this.getFileLength(4189053, 7189053);
        response.setContentType("application/x-msdownload"); 
        response.setHeader("Content-Length", lenf.toString());//文件大小值5几M
        response.setHeader("Content-Disposition", "attachment; filename="+java.net.URLEncoder.encode(name,"UTF-8"));  
        OutputStream out = response.getOutputStream();  
        byte[] buf = new byte[1024];  
        if (destUrl != null) {  
            BufferedInputStream br = bis;  
            int len = 0;  
            while ((len = br.read(buf)) > 0){  
                out.write(buf, 0, len);  
            }                 
            br.close();  
        }  
        out.flush();  
        out.close();  
  
    } 



//

  /**
     * 视频下载
     * by XnOU
     */
    @RequestMapping("/video/download2")
    public void downloadVideo2(HttpServletRequest request, HttpServletResponse response) throws IOException {
        String vid = ServletRequestUtils.getStringParameter(request, "vid", ""); //
        String df = ServletRequestUtils.getStringParameter(request, "df", "1"); //视频码率
        String fileName = ServletRequestUtils.getStringParameter(request, "fileName", "无限极视频"); //
        
        String fileFormat=(".mp4");
        String name=fileName.trim()+fileFormat;
        
        // set the content type
        response.setContentType("Content-Type: application/force-download");
        response.setHeader("Content-Disposition", "attachment; filename="+java.net.URLEncoder.encode(name,"UTF-8")); 
        
        // http://v.polyv.net/uc/video/getMp4?vid=5fa716fe381c1618befa75f8066554c0_5&df=2
        //String url = "http://v.polyv.net/uc/video/getMp4?vid=" + vid + "&df=" + df;
        String url = "http://mpv.videocc.net/5fa716fe38/0/5fa716fe381c1618befa75f8066554c0_1.mp4";
        
        URL videoUrl = new URL(url);
        
        BufferedInputStream bis = null;
        BufferedOutputStream bos = null;
        try {
            bis = new BufferedInputStream(videoUrl.openStream());
            bos = new BufferedOutputStream(response.getOutputStream());
            
            byte[] buf = new byte[2048];
            long totalBytes = 0L;
            int readBytes = -1;
            while((readBytes = bis.read(buf)) != -1) {
                bos.write(buf);
                totalBytes += readBytes;
            }
            
            bos.flush();
            logger.info("download total bytes: {}", totalBytes);
            
        }catch(IOException e) {
            logger.error("An error occurs when downloading a video, vid={}", vid, e);
            
        }finally {
            if(null != bis) {
                try{
                bis.close();
                }catch(Exception e) {
                    //忽略
                }
            }
            if(null != bos) {
                try {bos.close();
                }catch(Exception e) {
                    //忽略
                }
            }
        } 
    } 


	///

	    /**
     * 视频下载
     */
    //@RequestMapping("/video/download")
    //public void downloadVideo(HttpServletRequest request, HttpServletResponse response) throws IOException {  
        //String id = request.getParameter("id"); 
        /*String filePath = ServletRequestUtils.getStringParameter(request, "filePath", ""); //
        String fileName = ServletRequestUtils.getStringParameter(request, "fileName", ""); //
        String vid = ServletRequestUtils.getStringParameter(request, "vid", ""); //
        String df = ServletRequestUtils.getStringParameter(request, "df", "1"); //视频码率
        String destUrl = filePath;
        //LOG.info("-------1-------"+filePath); 
        destUrl=destUrl+"?vid="+vid+"&df="+df;
        String fileFormat=(".mp4");
        String name=fileName.trim()+fileFormat;
        //File f = new File(destUrl);
        //LOG.info("--------------"+f.getName());

        // 建立链接  
        URL url = new URL(destUrl);  
        HttpURLConnection httpUrl = (HttpURLConnection) url.openConnection();  
        // 连接指定的资源  
        httpUrl.connect();  
        
        
        // 获取网络输入流  
        BufferedInputStream bis = new BufferedInputStream(httpUrl.getInputStream());  
  
        Integer lenf=httpUrl.getContentLength();
        //LOG.info("--------len-------"+lenf);
        //String lenf=this.getFileLength(22489053, 72489053);
        response.setContentType("application/x-msdownload"); 
        response.setHeader("Content-Length", lenf.toString());//文件大小值20几M
        response.setHeader("Content-Disposition", "attachment; filename="+java.net.URLEncoder.encode(name,"UTF-8"));  
        OutputStream out = response.getOutputStream();  
        byte[] buf = new byte[1024];  
        if (destUrl != null) {  
            BufferedInputStream br = bis;  
            int len = 0;  
            while ((len = br.read(buf)) > 0){  
                out.write(buf, 0, len);  
            }                 
            br.close();  
        }  
        out.flush();  
        out.close();  */
    //} 

	///

	
    
  
    
    
    /**
     * 图片下载
     */
    @RequestMapping("/picture/download")
    public void downloadPicture(HttpServletRequest request, HttpServletResponse response) throws IOException {  
        //String id = request.getParameter("id"); 
        String filePath = ServletRequestUtils.getStringParameter(request, "filePath", ""); //
        String fileName = ServletRequestUtils.getStringParameter(request, "fileName", ""); //
        String courseId = ServletRequestUtils.getStringParameter(request, "courseId", ""); //
        
        Course course = courseManager.getCourse(courseId);
        if(null != course){
        	String userAgentStr = request.getHeader("user-agent");
        	UserAgent userAgent = UserAgent.parseUserAgentString(userAgentStr);
			String browser = userAgent.getBrowser().getName();
			
        	DownloadDataLog downloadDataLog = new DownloadDataLog();
        	downloadDataLog.setDownloadId(PrimaryKeyUtils.generateSequentialKey());
        	downloadDataLog.setCourseId(courseId);
        	downloadDataLog.setCourseType(course.getCourseType());
        	downloadDataLog.setTitle(course.getTitle());
        	downloadDataLog.setCategoryId(course.getCategoryId());
        	downloadDataLog.setCoverImage(course.getCoverImage());
        	downloadDataLog.setSourceUrl(request.getHeader("Referer"));
        	downloadDataLog.setUserIp(IPUtil.getRealIP(request));
        	downloadDataLog.setDefinition("");
        	downloadDataLog.setBrowser(browser);
        	if (UserAgentDetector.isMobile(userAgentStr)) {
        		downloadDataLog.setPlatformType(PlatformTypeStatus.MOBILE.getValue());
        	}else if (UserAgentDetector.isWeiXin(userAgentStr)) {
        		downloadDataLog.setPlatformType(PlatformTypeStatus.WEIXIN.getValue());
        	}else {
        		downloadDataLog.setPlatformType(PlatformTypeStatus.PC.getValue());
        	}
        	downloadDataLog.setUserAgent(userAgentStr);
        	downloadDataLog.setDateAdded(new Date());
        	boolean opStatus = downloadLogManager.addDownloadDataLog(downloadDataLog);
        	logger.info("New download record, courseId={}, opStatus={}", new Object[] { courseId, opStatus });
        	return;
        }
        
        String destUrl = filePath;
        //LOG.info("--------------"+filePath); 
        
        String fileFormat=filePath.substring(filePath.lastIndexOf("."));
        //String name=fileName.trim()+fileFormat;
        String name=filePath.substring(filePath.lastIndexOf("/")+1, filePath.length()); 
        //File f = new File(filePath);
        //response.setHeader("Content-Disposition", "attachment; filename="+java.net.URLEncoder.encode(f.getName(),"UTF-8"));  
        //LOG.info("--------------"+f.getName());

        // 建立链接  
        URL url = new URL(destUrl);  
        HttpURLConnection httpUrl = (HttpURLConnection) url.openConnection();  
        // 连接指定的资源  
        httpUrl.connect();  
        // 获取网络输入流  
        BufferedInputStream bis = new BufferedInputStream(httpUrl.getInputStream());  
  
        Integer lenf=httpUrl.getContentLength();
        //String lenf=this.getFileLength(4189053, 7189053);
        response.setContentType("application/x-msdownload"); 
        response.setHeader("Content-Length", lenf.toString());//文件大小值5几M
        response.setHeader("Content-Disposition", "attachment; filename="+java.net.URLEncoder.encode(name,"UTF-8"));
        OutputStream out = response.getOutputStream();
        byte[] buf = new byte[1024];  
        if (destUrl != null) {  
            BufferedInputStream br = bis;  
            int len = 0;  
            while ((len = br.read(buf)) > 0){  
                out.write(buf, 0, len);  
            }                 
            br.close();  
        }  
        out.flush();  
        out.close();  
  
    } 





### 回答1: chttplib是Python的一个HTTP客户端库,可以方便地在Python脚本中下载网络资源文件。使用该库可以高效地获取Web服务器上的文本、图片音频视频等各种类别的数据资源文件,可以方便地与远程服务器进行通信,并进行网页爬取等操作。 使用chttplib很简单,只需要导入httplib模块,然后创建一个HTTPConnection对象,并调用get()或post()方法即可实现获取Web服务器中的数据。我们可以提供一个URL以及一些可选参数,比如请求头等,以获取我们想要的资源。另外,还可以设置代理服务器、超时时间等属性。 chttplib的优点在于它支持Python中的多线程、非阻塞IO等常见的编程方式,保证了程序的高效性和可扩展性。同时,它也提供了可以定制的异常处理机制,比如HTTPError和URLError等,使得我们可以更方便、更准确地追踪异常并进行错误处理。 不过需要注意的是,在使用chttplib进行数据下载时,我们需要了解Web服务器的返回格式(比如HTML、JSON等)并进行适当的解析处理,以满足我们的业务需求。此外,为了避免对Web服务器的负担过大,我们应当使用合理的下载频率和下载量,并遵守相关的网络规则和法律法规。 ### 回答2: chttplib是Python的一个库,用于HTTP客户端编程。该库允许开发者在Python代码中实现HTTP应用程序,包括创建HTTP连接、发送HTTP请求和处理HTTP响应等。 使用chttplib进行下载操作是非常简单的。创建HTTP连接之后,只需要发送GET请求获取资源,并将获取到的响应保存到本地即可。 首先,需要导入chttplib库并创建HTTP连接: ``` import httplib conn = httplib.HTTPConnection("www.example.com") ``` 接下来,发送GET请求获取资源: ``` conn.request("GET", "/download/file.pdf") response = conn.getresponse() data = response.read() ``` 最后,将获取到的响应数据保存到本地: ``` with open("file.pdf", "wb") as f: f.write(data) ``` 这样,就完成了使用chttplib进行下载操作的过程。在实际应用中,还需要进行异常处理、文件名和路径的处理等操作,以确保下载操作能够正常进行。 ### 回答3: chttplib是一个Python标准库,用于进行HTTP和HTTPS通信。它提供了多种函数和类来方便地创建HTTP请求和处理HTTP响应。使用chttplib,我们可以轻松地下载和上传文件,获取网页内容,以及进行其他HTTP操作。 在使用chttplib进行下载时,可以通过创建HTTP连接对象来发送HTTP请求,并获取HTTP响应。HTTP响应的内容会被保存到一个文件中。通常,使用该库我们可以实现在Python中通过HTTP协议下载网页或文件。 此外,chttplib还提供了多种处理HTTP响应的方法,如获取响应头信息、状态码等。它具有良好的可扩展性和灵活性,可以满足一些特殊的HTTP请求需求。 总之,chttplib是Python中处理HTTP和HTTPS通信的一种强大工具,它可以轻松实现从网站上下载、上传和处理文件等操作。如果需要进行这些操作,chttplib是一个值得考虑的选择。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值