在unity 中,使用http請求,下載文件到可讀可寫路徑


在這里我用了一個線程池,線程池參數接收一個帶有object參數的,無返回值的委托 ,下載用到的核心代碼,網上拷貝的,他的核心就是發起一個web請求,然后得到請求的響應,讀取響應的流

剩下的都是常見的IO操作

 

 

 

由於線程池接參數的委托,接收一個object參數。所以,我把請求地址和本地存放地址以及名字,封裝了一個類,用來傳參

 

 這是下載工具代碼,如下

using System;
using System.Collections;
using System.Collections.Generic;
using System.IO;
using System.Net;
using UnityEngine;


public class DownLoaderEnum
{
    public string url;
    public string path;
    public DownLoaderEnum(string URL, string PATH)
    {
        url = URL;
        path = PATH;
    }
}

public class HttpDownload
{


    /// <summary>
    /// http下載文件
    /// </summary>
    /// <param name="url">下載文件地址</param>
    /// <param name="path">文件存放地址,包含文件名</param>
    /// <returns></returns>
    public void HttpDownloader(object down)
    {
        if (!Directory.Exists((down as DownLoaderEnum).path))
            Directory.CreateDirectory((down as DownLoaderEnum).path);
        string tempPath = System.IO.Path.GetDirectoryName((down as DownLoaderEnum).path) + @"\temp";
        System.IO.Directory.CreateDirectory(tempPath);  //創建臨時文件目錄
        string tempFile = tempPath + @"\" + System.IO.Path.GetFileName((down as DownLoaderEnum).path) + ".temp"; //臨時文件

        if (System.IO.File.Exists(tempFile))
        {
            System.IO.File.Delete(tempFile);    //存在則刪除
        }
        try
        {
            FileStream fs = new FileStream(tempFile, FileMode.Append, FileAccess.Write, FileShare.ReadWrite);
            // 設置參數
            HttpWebRequest request = WebRequest.Create((down as DownLoaderEnum).url) as HttpWebRequest;
            //發送請求並獲取相應回應數據
            HttpWebResponse response = request.GetResponse() as HttpWebResponse;
            //直到request.GetResponse()程序才開始向目標網頁發送Post請求
            Stream responseStream = response.GetResponseStream();
            //創建本地文件寫入流
            //Stream stream = new FileStream(tempFile, FileMode.Create);
            byte[] bArr = new byte[1024];
            int size = responseStream.Read(bArr, 0, (int)bArr.Length);
            while (size > 0)
            {
                //stream.Write(bArr, 0, size);
                fs.Write(bArr, 0, size);
                size = responseStream.Read(bArr, 0, (int)bArr.Length);
            }
            //stream.Close();
            fs.Close();
            responseStream.Close();
            string suffixName = (down as DownLoaderEnum).url;
            int su = suffixName.LastIndexOf('/');
            suffixName = (down as DownLoaderEnum).path+suffixName.Substring(su);
           // Debug.LogError(suffixName);
            System.IO.File.Move(tempFile, suffixName);
            // return true;
            Debug.LogError("下載完成");
        }
        catch (Exception ex)
        {
            Debug.LogError("錯誤==>>" + ex.Message);
            //return false;
        }
    }
}

  

  這是測試代碼

using System;
using System.Collections;
using System.Collections.Generic;
using System.IO;
using System.Threading;
using UnityEngine;

public class NewBehaviourScript : MonoBehaviour {
    public string url = "http://dl172.80s.im:920/1802/[比得兔]劇場預告片/[比得兔]劇場預告片_hd.mp4";
    // Use this for initialization
    string path = "";
    HttpDownload download = new HttpDownload();
    DownLoaderEnum down;
    private void Awake()
    {
        path = Application.streamingAssetsPath;
        //DirectoryInfo directory = new DirectoryInfo(path);
        //if (directory.Exists)
        //    directory.Create();
        //Debug.LogError(path);
    }
    // Use this for initialization
    void Start()
    {
        ThreadPool.SetMaxThreads(5, 5);
        down = new DownLoaderEnum(url, path);//請求url,存放地址,存放文件名
    }

    // Update is called once per frame
    void Update()
    {
        if (Input.GetKeyDown(KeyCode.Space))
        {
            ThreadPool.QueueUserWorkItem(download.HttpDownloader, down);
        }
    }
}

  

  

 可以看到,已經下載完成

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM