在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);
        }
    }
}

  

  

 可以看到,已经下载完成

 

posted @ 2018-02-22 14:33  飞天艾特小猪  阅读(6059)  评论(0编辑  收藏  举报