$ C $下从Youtube下载视频的Java,Android的 [英] Code for download video from Youtube on Java, Android

查看:265
本文介绍了$ C $下从Youtube下载视频的Java,Android的的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我创造了$ C $下从Youtube下载视频,但是这code不与无线网络连接的工作,并与手机连接使用。在哪里我错了吗?

 进口的java.io.File;
进口java.io.FileOutputStream中;
进口java.io.IOException异常;
进口的java.io.InputStream;
进口java.io.InputStreamReader中;
进口java.net.HttpURLConnection中;
进口java.net.MalformedURLException;
进口的java.net.URL;
进口的java.util.Enumeration;
进口java.util.Vector中;

进口android.app.Activity;
进口android.app.ProgressDialog;
进口android.net.Uri;
进口android.os.AsyncTask;
进口android.os.Bundle;
进口android.util.Log;
进口android.widget.MediaController;
进口android.widget.VideoView;

公共类MyActivity延伸活动{

    私有类ReceivingDataFromYoutube扩展的AsyncTask<字符串,太虚,太虚> {

        私人ProgressDialog对话框=新ProgressDialog(MyActivity.this);
        私人字符串的结果;

        在preExecute保护无效(){
            dialog.setMessage(下载...);
            dialog.show();
        }

        @覆盖
        保护无效doInBackground(字符串...为arg0){
            INT开始,结束;
            字符串tmpstr = NULL;
            尝试 {
                网址URL =新的URL(http://www.youtube.com/watch?v=y12-1miZHLs&nomobile=1);
                HttpURLConnection的CON =(HttpURLConnection类)url.openConnection();
                con.setRequestMethod(GET);
                InputStream的流= con.getInputStream();
                InputStreamReader的读者=新的InputStreamReader(流);
                StringBuffer的缓冲区=新的StringBuffer();
                的char [] buf中=新的char [262144]。
                INT chars_read;
                而((chars_read = reader.read(buf中,0,262144))!=  -  1){
                    buffer.append(BUF,0,chars_read);
                }
                tmpstr = buffer.toString();

                开始= tmpstr.indexOf(url_en coded_fmt_stream_map =);
                结束= tmpstr.indexOf(&放大器;,开始+ 27);
                如果(完== -1){
                    结束= tmpstr.indexOf(\,开始+ 27);
                }
                tmpstr = UtilClass.URLDe code(tmpstr.substring(开始+ 27,结束));

            }赶上(MalformedURLException异常E){
                抛出新的RuntimeException();
            }赶上(IOException异常E){
                抛出新的RuntimeException();
            }

            矢量url_en coded_fmt_stream_map =新的向量();
            开始= 0;
            端= tmpstr.indexOf(,);

            而(完!=  -  1){
                url_en coded_fmt_stream_map.addElement(tmpstr.substring(开始,结束));
                开始=结束+ 1;
                结束= tmpstr.indexOf(,开始);
            }

            url_en coded_fmt_stream_map.addElement(tmpstr.substring(开始,tmpstr.length()));
            字符串结果=;
            枚举url_en coded_fmt_stream_map_enum = url_en coded_fmt_stream_map.elements();
            而(url_en coded_fmt_stream_map_enum.hasMoreElements()){
                tmpstr =(字符串)url_en coded_fmt_stream_map_enum.nextElement();
                开始= tmpstr.indexOf(ITAG =);
                如果(开始!=  -  1){
                    结束= tmpstr.indexOf(&放大器;,开始+ 5);

                    如果(完== -1){
                          结束= tmpstr.length();
                    }

                    INT FMT =的Integer.parseInt(tmpstr.substring(开始+ 5月底));

                    如果(FMT == 35){
                        开始= tmpstr.indexOf(URL =);
                        如果(开始!=  -  1){
                            结束= tmpstr.indexOf(&放大器;,开始+ 4);
                            如果(完== -1){
                               结束= tmpstr.length();
                            }
                            结果= UtilClass.URLDe code(tmpstr.substring(开始+ 4,结束));
                            this.result =结果;
                            打破;
                        }
                    }
                }
            }
            尝试 {
              网址U =新的URL(结果);
              HttpURLConnection的C =(HttpURLConnection类)u.openConnection();
              c.setRequestMethod(GET);
/ * c.setRequestProperty(Youtubedl-NO-COM pression,真);
              c.setRequestProperty(用户代理,YouTube的); * /

              c.setDoOutput(真正的);
              c.connect();

              FileOutputStream中F =新的FileOutputStream(新文件(/ SD卡/ 3.flv));

              在的InputStream = c.getInputStream();
              byte []的缓冲区=新的字节[1024];
              INT SZ = 0;
              而((SZ = in.read(缓冲液))大于0){
                   f.write(缓冲液,0,SZ);
              }
              f.close();
            }赶上(MalformedURLException异常E){
                新的RuntimeException();
            }赶上(IOException异常E){
                新的RuntimeException();
            }
            返回null;
        }

        保护无效onPostExecute(作废不用){
            dialog.dismiss();
        }

    }


    @覆盖
    公共无效的onCreate(包savedInstanceState){
        super.onCreate(savedInstanceState);
        的setContentView(R.layout.main);

        新ReceivingDataFromYoutube()执行()。
    }
}
 

解决方案

3个步骤:

  1. 检查SORCE code YouTube网站(HTML),你会得到这样的链接(HTTP%253A%252F%252Fo-O。preferred.telemar,cnf1.v18.lscache6 .c.youtube.com%252Fvideoplayback ...);

  2. 德code中的URL(删除codeS%2B,%25等)中,创建一个德codeR与codeS:的 http://www.w3schools.com/tags/ref_urlen$c$c.asp 和使用功能 Uri.de code(URL)以代替无效转义八位组;

  3. 使用的code下载流:

      URL U = NULL;
    InputStream的是= NULL;
    
    尝试 {
        U =新的URL(网址);
        是= u.openStream();
        HttpURLConnection的HUC =(HttpURLConnection类)u.openConnection(); //知道视频的大小
        INT大小= huc.getContentLength();
    
        如果(HUC!= NULL){
            字符串文件名=FILE.mp4;
            。字符串storagePath = Environment.getExternalStorageDirectory()的toString();
            文件F =新的文件(storagePath,文件名);
    
            FileOutputStream中FOS =新的FileOutputStream(F);
            byte []的缓冲区=新的字节[1024];
            INT LEN1 = 0;
            如果(是!= NULL){
                而((LEN1 = is.​​read(缓冲液))大于0){
                    fos.write(缓冲液,0,LEN1);
                }
            }
            如果(FOS!= NULL){
                fos.close();
            }
        }
    }赶上(MalformedURLException的MUE){
        mue.printStackTrace();
    }赶上(IOException异常IOE){
        ioe.printStackTrace();
    } 最后 {
        尝试 {
            如果(是!= NULL){
                is.close();
            }
        }赶上(IOException异常IOE){
            //只是要忽略这个
        }
    }
     

这就是全部,大部分的东西,你会发现在网络上!

I created code for download video from Youtube, but this code doesn't work with Wi-fi connection and work with mobile connection. Where did I have mistake?

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.Enumeration;
import java.util.Vector;

import android.app.Activity;
import android.app.ProgressDialog;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.widget.MediaController;
import android.widget.VideoView;

public class MyActivity extends Activity {

    private class ReceivingDataFromYoutube extends AsyncTask<String, Void, Void> {

        private ProgressDialog dialog = new ProgressDialog(MyActivity.this);
        private String result;

        protected void onPreExecute() {
            dialog.setMessage("Downloading...");
            dialog.show();
        }

        @Override
        protected Void doInBackground(String... arg0) {
            int begin, end;
            String tmpstr = null;
            try {
                URL url=new URL("http://www.youtube.com/watch?v=y12-1miZHLs&nomobile=1");
                HttpURLConnection con = (HttpURLConnection) url.openConnection();
                con.setRequestMethod("GET");
                InputStream stream=con.getInputStream();
                InputStreamReader reader=new InputStreamReader(stream);
                StringBuffer buffer=new StringBuffer();
                char[] buf=new char[262144];                
                int chars_read;
                while ((chars_read = reader.read(buf, 0, 262144)) != -1) {
                    buffer.append(buf, 0, chars_read);
                }
                tmpstr=buffer.toString();

                begin  = tmpstr.indexOf("url_encoded_fmt_stream_map=");
                end = tmpstr.indexOf("&", begin + 27);
                if (end == -1) {
                    end = tmpstr.indexOf("\"", begin + 27);
                }
                tmpstr = UtilClass.URLDecode(tmpstr.substring(begin + 27, end));

            } catch (MalformedURLException e) {
                throw new RuntimeException();
            } catch (IOException e) {
                throw new RuntimeException();
            }

            Vector url_encoded_fmt_stream_map = new Vector();
            begin = 0;
            end   = tmpstr.indexOf(",");

            while (end != -1) {
                url_encoded_fmt_stream_map.addElement(tmpstr.substring(begin, end));
                begin = end + 1;
                end   = tmpstr.indexOf(",", begin);
            }

            url_encoded_fmt_stream_map.addElement(tmpstr.substring(begin, tmpstr.length()));
            String result = "";
            Enumeration url_encoded_fmt_stream_map_enum = url_encoded_fmt_stream_map.elements();
            while (url_encoded_fmt_stream_map_enum.hasMoreElements()) {
                tmpstr = (String)url_encoded_fmt_stream_map_enum.nextElement();
                begin = tmpstr.indexOf("itag=");
                if (begin != -1) {
                    end = tmpstr.indexOf("&", begin + 5);

                    if (end == -1) {
                          end = tmpstr.length();
                    }

                    int fmt = Integer.parseInt(tmpstr.substring(begin + 5, end));

                    if (fmt == 35) {
                        begin = tmpstr.indexOf("url=");
                        if (begin != -1) {
                            end = tmpstr.indexOf("&", begin + 4);
                            if (end == -1) {
                               end = tmpstr.length();
                            }
                            result = UtilClass.URLDecode(tmpstr.substring(begin + 4, end));
                            this.result=result;
                            break;
                        }
                    }
                }
            }         
            try {
              URL u = new URL(result);
              HttpURLConnection c = (HttpURLConnection) u.openConnection();
              c.setRequestMethod("GET");
/*              c.setRequestProperty("Youtubedl-no-compression", "True");
              c.setRequestProperty("User-Agent", "YouTube");*/

              c.setDoOutput(true);
              c.connect();

              FileOutputStream f=new FileOutputStream(new File("/sdcard/3.flv"));

              InputStream in=c.getInputStream();
              byte[] buffer=new byte[1024];
              int sz = 0;
              while ( (sz = in.read(buffer)) > 0 ) {
                   f.write(buffer,0, sz);
              }
              f.close();
            } catch (MalformedURLException e) {
                new RuntimeException();
            } catch (IOException e) {
                new RuntimeException();
            }
            return null;
        }

        protected void onPostExecute(Void unused) {
            dialog.dismiss();
        }    

    }


    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);

        new ReceivingDataFromYoutube().execute();
    }   
}  

解决方案

3 steps:

  1. Check the sorce code (HTML) of YouTube, you'll get the link like this (http%253A%252F%252Fo-o.preferred.telemar-cnf1.v18.lscache6.c.youtube.com%252Fvideoplayback ...);

  2. Decode the url (remove the codes %2B,%25 etc), create a decoder with the codes: http://www.w3schools.com/tags/ref_urlencode.asp and use the function Uri.decode(url) to replace invalid escaped octets;

  3. Use the code to download stream:

    URL u = null;
    InputStream is = null;  
    
    try {
        u = new URL(url);
        is = u.openStream(); 
        HttpURLConnection huc = (HttpURLConnection)u.openConnection(); //to know the size of video
        int size = huc.getContentLength();                 
    
        if(huc != null) {
            String fileName = "FILE.mp4";
            String storagePath = Environment.getExternalStorageDirectory().toString();
            File f = new File(storagePath,fileName);
    
            FileOutputStream fos = new FileOutputStream(f);
            byte[] buffer = new byte[1024];
            int len1 = 0;
            if(is != null) {
                while ((len1 = is.read(buffer)) > 0) {
                    fos.write(buffer,0, len1);  
                }
            }
            if(fos != null) {
                fos.close();
            }
        }                       
    } catch (MalformedURLException mue) {
        mue.printStackTrace();
    } catch (IOException ioe) {
        ioe.printStackTrace();
    } finally {
        try {               
            if(is != null) {
                is.close();
            }
        } catch (IOException ioe) {
            // just going to ignore this one
        }
    }
    

That's all, most of stuff you'll find on the web!!!

这篇关于$ C $下从Youtube下载视频的Java,Android的的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆