您的位置:首页 > 理论基础 > 计算机网络

unity3d 通过 http网络下载到本地

2016-08-18 15:26 417 查看
最近研究了下http 从服务器下载到本地。
有点复杂,没太搞明白  post,  不过也做了个demo......
 
用到了 2种方式 :
1,   http get
2,   www 
 



 
第一种:
     http  get
 
    string urlPath = "http://www........";//写个网络资源路径(自己写)
    string localPath = @"D:\BianZhen.mov";
      /// <summary>
    /// 下载文件
    /// </summary>
    IEnumerator DownLoadFile(string url)
    {
        HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create(url);
        request.Method= "GET";
        HttpWebResponse hw = (HttpWebResponse)request.GetResponse();
        Stream stream =hw.GetResponseStream();
        FileStream fileStream = new FileStream(localPath, FileMode.Create, FileAccess.Write);
        long length = hw.ContentLength;
        long currentNum = 0;
        decimal currentProgress = 0;
 
        while (currentNum < length)
        {
            byte[] buffer = new byte[1024];
           currentNum += stream.Read(buffer, 0, buffer.Length);
           fileStream.Write(buffer, 0, buffer.Length);
            if (currentNum % 1024 == 0)
           {
               currentProgress = Math.Round(Convert.ToDecimal(Convert.ToDouble(currentNum) / Convert.ToDouble(length)
* 100), 4);
                Debug.Log("当前下载文件大小:" + length.ToString() + "字节   当前下载大小:" +
currentNum + "字节 下载进度" + currentProgress.ToString()
+ "%");
           }
            else
           {
                Debug.Log("当前下载文件大小:" + length.ToString() + "字节   当前下载大小:" +
currentNum + "字节"+ "字节 下载进度" +
100 + "%");
           }
           currentnn = currentProgress;
            yield return false;
        }
        hw.Close();
       stream.Close();
       fileStream.Close();
    }
    decimal currentNumShow;
    GUIStyle guistyle = new GUIStyle();
    void OnGUI()
    {
       guistyle.fontSize = 80;
        GUI.Label(new Rect(50, 50, 50, 50),currentNumShow.ToString(), guistyle);
    }
 
第二种:
     www
 
    string urlPath = "http://www.....";//资源网络路径(自己写)
    string file_SaveUrl = @"D:\test.rar";//资源保路径
    FileInfo file; 
    void Start ()
    {
        file = new FileInfo(file_SaveUrl);
        Debug.Log(file_SaveUrl);
       StartCoroutine(DownFile(urlPath));
    }
    /// <summary>
    /// 下载文件
    /// </summary>
    IEnumerator DownFile(string url)
    {
        WWW www = new WWW(url);
        yield return www;
        if (www.isDone)
        {
            Debug.Log("下载完成");
            byte[] bytes = www.bytes;
           CreatFile(bytes);
        }
    }
    /// <summary>
    /// 创建文件
    /// </summary>
    /// <paramname="bytes"></param>
    void CreatFile(byte[] bytes)
    {
        Stream stream;
        stream =file.Create();
       stream.Write(bytes, 0, bytes.Length);
       stream.Close();
       stream.Dispose();
}
 
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  unity下载 http下载