java - 从服务器下载mp4并将其保存到sd卡

标签 java android fileinputstream fileoutputstream

我只是想从服务器下载 mp4 或 .3gp 文件到 Android 设备。我尝试了多种方法来实现,但在某些情况下它会给出IOException,有时会给出 ProtocolException

使用 DownloadVideoTask.class 下载视频的第一种方法

public class DownloadVideoTask extends AsyncTask<String, Integer, Boolean>
{
    String nameOfSong;

    Context context;

    Boolean flage = true;

    ProgressDialog progressDialog2;

    @SuppressLint("InlinedApi")
    public DownloadVideoTask(Context context,String trackTitle)
    {
        this.context = context; 

        nameOfSong = trackTitle;
    }

    @Override
    protected void onPreExecute()
    {
        super.onPreExecute();

        if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB)
        {
            progressDialog2 = new ProgressDialog(context, AlertDialog.THEME_HOLO_LIGHT);
        }
        else
        {
            progressDialog2 = new ProgressDialog(context);
        }

        progressDialog2.setIndeterminate(false);

        progressDialog2.setMax(100);

        progressDialog2.setTitle("Please wait...");

        try
        {
            progressDialog2.setMessage("Downloding.. " + nameOfSong.substring(0, 20));
        }
        catch (Exception e)
        {
            progressDialog2.setMessage("Downloding Song...." );
        }


        progressDialog2.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);

        progressDialog2.show();

    }

    @Override
    protected Boolean doInBackground(String... params)
    {
/*      String trackTitle = params[0];

        nameOfSong = trackTitle;
*/
        String trackUrl = params[0];

        try
        {
            File root;// = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS);

            if(Build.VERSION.SDK_INT < Build.VERSION_CODES.HONEYCOMB)
            {
                root = Environment.getExternalStorageDirectory();
            }
            else
            {
                root = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS);
            }

            File dir = new File(root.getAbsolutePath() + "/XarDownloder");

            if (dir.exists() == false)
            {
                dir.mkdirs();
            }

            URL url = new URL(trackUrl);

            File file = new File(dir, nameOfSong);

            URLConnection urlConnection = url.openConnection();

            int fileLength = urlConnection.getContentLength();//ye statement inputStream k bad likhi thi

            InputStream inputStream = urlConnection.getInputStream();



            OutputStream outputStream = new FileOutputStream(
                    root.getAbsolutePath() +  "/XarDownloder/" + nameOfSong
                            + ".mp4");

            byte data[] = new byte[1024];
            long total = 0;
            int count;
            while ((count = inputStream.read(data)) != -1)
            {
                total += count;
                // publishing the progress....
                publishProgress((int) (total * 100 / fileLength));

                outputStream.write(data, 0, count);
            }

            outputStream.flush();
            outputStream.close();
            inputStream.close();


            try
            {
                if(Build.VERSION.SDK_INT < Build.VERSION_CODES.HONEYCOMB)
                {
                    context.sendBroadcast(new Intent(Intent.ACTION_MEDIA_MOUNTED,
                              Uri.parse("file://"+ Environment.getExternalStorageDirectory())));
                }
                else
                {
                    context.sendBroadcast(new Intent(Intent.ACTION_MEDIA_MOUNTED,Uri.parse("file://" + Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_MUSIC))));
                }

                context.sendBroadcast(new Intent(
                        Intent.ACTION_MEDIA_SCANNER_SCAN_FILE, Uri
                                .fromFile(file)));

            }
            catch (Exception e)
            {

            }

            return true;

        }
        catch (IOException e)
        {

            flage = false;

            e.printStackTrace();
        }

        return false;
    }

    @Override
    protected void onPostExecute(Boolean result)
    {
        super.onPostExecute(result);

        if (result)
        {
            try
            {
                Toast.makeText(context,
                        nameOfSong.substring(0, 30) + "Downloaded...",
                        Toast.LENGTH_LONG).show();
            }
            catch (Exception e)
            {
                Toast.makeText(context,
                          "Song Downloaded...",
                        Toast.LENGTH_LONG).show();
            }
        }
        else
        {

            Toast.makeText(context, "Sorry, song is not downloadable",
                    Toast.LENGTH_LONG).show();
        }

        progressDialog2.dismiss();
    }

    @Override
    protected void onProgressUpdate(Integer... values)
    {
        super.onProgressUpdate(values);

        progressDialog2.setProgress(values[0]);
    }
}

使用 DownloadFile 的第二种方法

public class DownloadFile extends AsyncTask<String, Integer, String>
{
    String videoToDownload = "http://r2---sn-u2oxu-f5f6.googlevideo.com/videoplayback?expire=1438261718&fexp=901816,9405637,9407538,9407942,9408513,9408710,9409172,9413020,9414764,9414856,9414935,9415365,9415485,9416126,9416355,9417009,9417719,9418201,9418204&id=d813f7f3bef428da&mn=sn-u2oxu-f5f6&mm=31&mime=video/mp4&upn=82UaibRK7EM&itag=18&pl=24&dur=148.189&ip=167.114.5.145&key=yt5&ms=au&mt=1438239687&mv=u&source=youtube&ipbits=0&pcm2cms=yes&sparams=dur,id,ip,ipbits,itag,lmt,mime,mm,mn,ms,mv,pcm2cms,pl,ratebypass,source,upn,expire&lmt=1428049239028653&signature=39087CBD9BDC9EBD612CA0E8E82AC692B427FFE3.18C23CD0AEC8410CFBE4F35F532199DFF21E7DFA&ratebypass=yes&sver=3&signature=&title=How+To+Train+Your+Dragon+2+Official+Trailer+%231+%282014%29+-+Animation+Sequel+HD&filename=How_To_Train_Your_Dragon_2_Official_Trailer_1_2014__Animation_Sequel_HD.mp4";

    public DownloadFile()
    {

    }
    @Override
    protected String doInBackground(String... params)
    {
        int count;

        try
        {
            mp4load(videoToDownload);
        }
        catch (Exception e)
        {
            // TODO: handle exception
        }

        /*try
        {
            URL url = new URL(videoToDownload);
            URLConnection conexion = url.openConnection();
            conexion.connect();
            // this will be useful so that you can show a tipical 0-100%
            // progress bar
            int lenghtOfFile = conexion.getContentLength();

            // downlod the file
            InputStream input = new BufferedInputStream(url.openStream());
            OutputStream output = new FileOutputStream("/sdcard/xarwere/firstdownload.mp4");

            byte data[] = new byte[1024];

            long total = 0;

            while ((count = input.read(data)) != -1)
            {
                total += count;
                // publishing the progress....
                publishProgress((int) (total * 100 / lenghtOfFile));
                output.write(data, 0, count);
            }

            output.flush();
            output.close();
            input.close();
        }
        catch (Exception e)
        {
            e.printStackTrace();
        }*/
        return null;
    }

    public void mp4load(String urling)
    {
        try

        {
            URL url = new URL(urling);
            HttpURLConnection con = (HttpURLConnection) url.openConnection();
            con.setRequestMethod("GET");
            //c.setDoOutput(true);
            con.connect();

            String PATH = Environment.getExternalStorageDirectory()
                    + "/download/";
            //Log.v(LOG_TAG, "PATH: " + PATH);
            File file = new File(PATH);
            file.mkdirs();


            String fileName = "test.mp4";


            File outputFile = new File(file, fileName);

            if (!outputFile.exists())
            {
                outputFile.createNewFile();
            } 
            FileOutputStream fos = new FileOutputStream(outputFile);

            int status = con.getResponseCode();//my doctory

            InputStream is = con.getInputStream();



            byte[] buffer = new byte[1024];
            int len1 = 0;
            while ((len1 = is.read(buffer)) != -1) {
                fos.write(buffer, 0, len1);
            }
            fos.close();
            is.close();
        }
        catch (MalformedURLException e)
        {
            e.printStackTrace();
        }
        catch (ProtocolException e)
        {
            e.printStackTrace();
        }
        catch (IOException e1)
        {
            e1.printStackTrace();
        }
    }   
}

Where videoToDownload in DownloadFile.class is the URLi want to download. but at inputStream it gives exception.

我称这些为 AsyncTask

new DownloadFile().execute();

new DownloadVideoTask(TestingActivity.this, "nameofsong").execute("http://r2---sn-u2oxu-f5f6.googlevideo.com/videoplayback?expire=1438261718&fexp=901816,9405637,9407538,9407942,9408513,9408710,9409172,9413020,9414764,9414856,9414935,9415365,9415485,9416126,9416355,9417009,9417719,9418201,9418204&id=d813f7f3bef428da&mn=sn-u2oxu-f5f6&mm=31&mime=video/mp4&upn=82UaibRK7EM&itag=18&pl=24&dur=148.189&ip=167.114.5.145&key=yt5&ms=au&mt=1438239687&mv=u&source=youtube&ipbits=0&pcm2cms=yes&sparams=dur,id,ip,ipbits,itag,lmt,mime,mm,mn,ms,mv,pcm2cms,pl,ratebypass,source,upn,expire&lmt=1428049239028653&signature=39087CBD9BDC9EBD612CA0E8E82AC692B427FFE3.18C23CD0AEC8410CFBE4F35F532199DFF21E7DFA&ratebypass=yes&sver=3&signature=&title=How+To+Train+Your+Dragon+2+Official+Trailer+%231+%282014%29+-+Animation+Sequel+HD&filename=How_To_Train_Your_Dragon_2_Official_Trailer_1_2014__Animation_Sequel_HD.mp4");

最佳答案

我稍微修改了你的代码,但它可以很好地下载文件。您添加了互联网权限吗?

public class DownloadFile extends AsyncTask<String, Integer, String> {
    String videoToDownload = "http://r2---sn-u2oxu-f5f6.googlevideo.com/videoplayback?expire=1438261718&fexp=901816,9405637,9407538,9407942,9408513,9408710,9409172,9413020,9414764,9414856,9414935,9415365,9415485,9416126,9416355,9417009,9417719,9418201,9418204&id=d813f7f3bef428da&mn=sn-u2oxu-f5f6&mm=31&mime=video/mp4&upn=82UaibRK7EM&itag=18&pl=24&dur=148.189&ip=167.114.5.145&key=yt5&ms=au&mt=1438239687&mv=u&source=youtube&ipbits=0&pcm2cms=yes&sparams=dur,id,ip,ipbits,itag,lmt,mime,mm,mn,ms,mv,pcm2cms,pl,ratebypass,source,upn,expire&lmt=1428049239028653&signature=39087CBD9BDC9EBD612CA0E8E82AC692B427FFE3.18C23CD0AEC8410CFBE4F35F532199DFF21E7DFA&ratebypass=yes&sver=3&signature=&title=How+To+Train+Your+Dragon+2+Official+Trailer+%231+%282014%29+-+Animation+Sequel+HD&filename=How_To_Train_Your_Dragon_2_Official_Trailer_1_2014__Animation_Sequel_HD.mp4";

    @Override
    protected String doInBackground(String... params) {
        int count;

        try {
            mp4load(videoToDownload);
        } catch (Exception e) {
            // TODO: handle exception
        }

        return null;
    }

    public void mp4load(String urling) {
        try {
            URL url = new URL(urling);
            HttpURLConnection con = (HttpURLConnection) url.openConnection();
            con.setRequestMethod("GET");
            //c.setDoOutput(true);
            con.connect();

            String downloadsPath = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS).getAbsolutePath();

            String fileName = "test.mp4";

            File outputFile = new File(downloadsPath, fileName);

            if (!outputFile.exists()) {
                outputFile.createNewFile();
            }

            FileOutputStream fos = new FileOutputStream(outputFile);

            int status = con.getResponseCode();

            InputStream is = con.getInputStream();

            byte[] buffer = new byte[1024];
            int len1 = 0;
            while ((len1 = is.read(buffer)) != -1) {
                fos.write(buffer, 0, len1);
            }
            fos.close();
            is.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

关于java - 从服务器下载mp4并将其保存到sd卡,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31718850/

相关文章:

java - Spring Cloud Pass参数

Java 从字符串中解决数学运算

android - 当标记超出屏幕时如何移动相机?

android - 包括AAR lib编译错误: no resource identifier found

android - “ignoreKotlinNullability”实际做什么?

java - 使用 ini4j 的单例模式

java - 从文件输入流,到文件输出流

java - 文件输入流返回 null

java - Eclipse:如何检测项目是工作区的一部分

java - 在android中编辑简单列表中的文本