在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);
}
}
}
可以看到,已经下载完成


在unity 中,使用http请求,下载文件到可读可写路径的更多相关文章
- 如何使用post请求下载文件
使用get请求下载文件非常简便,但是get请求的url有长度和大小的限制,所以当请求参数非常多时无法满足需求,所以改成post请求const res = await fetch('xxxxxxxxx' ...
- 在Unity中使用LitJson解析json文件
LitJson 这个库需要找资源,找到LitJson.dll后将它放在Assets文件夹下,在脚本中使用using引入即可 测试代码 json文件: {"Archice":[{&q ...
- Python open()函数文件打开、读、写操作详解
一.Python open()函数文件打开操作 打开文件会用到open函数,标准的python打开文件语法如下:open(name[,mode[,buffering]])open函数的文件名是必须的, ...
- java创建TXT文件并进行读、写、修改操作
import java.io.*; /** * * 功能描述:创建TXT文件并进行读.写.修改操作 * * @author <a href="mailto:zha ...
- [转]JSP或servlet中(以及上传下载文件)中文乱码或不显示的解决方案
时间 2014-04-14 14:33:44 CSDN博客 原文 http://blog.csdn.net/xby1993/article/details/23677375 主题 ServletJ ...
- 把页面上的图表导出为pdf文件,分享一种请求下载文件的方法
最近客户提出一个需求,就是把页面上的图表导出为pdf文件. 找了很多资料.终于有了点头绪.最主要是参考了HighCharts的做法.http://www.hcharts.cn/ 实现原理:把页面图表的 ...
- js发送post请求下载文件
大家都知道ajax是不能直接下载文件的,所以一般都是通过一个超链接的形式去下载一个文件 但是当牵扯到需要发送很多数据到服务器上再下载的时候超链接的形式就有些太过勉强了 如下是一个工具方法(依赖jque ...
- java中使用springmvc实现下载文件
下载文件具体实现代码: public class TestDownload{ public HttpServletRequest request; public HttpServletResponse ...
- C# 中从网络上下载文件保存到本地文件
下面是C#中常用的从Internet上下载文件保存到本地的一些方法,没有太多的技巧. 1.通过 WebClient 类下载文件 WebClient webClient = new WebClien ...
随机推荐
- Java基础 - 强引用、弱引用、软引用、虚引用
1.强引用(StrongReference) 强引用是使用最普遍的引用. 假设一个对象具有强引用.那垃圾回收器绝不会回收它.例如以下: [java] view plaincopyprint" ...
- tonymillion/Reachability的使用
tonymillion/Reachability是GitHub上的一个开源工具类,目測是依据Apple的Reachability Demo改写而成. 该类能够測试到某一网络.主机等的可达性,支持Blo ...
- diamond源码阅读-获取服务器列表
serverAddressProcessor public synchronized void start() { if (isRun) { return; } isRun = true; initH ...
- 循环杀死Mysql sleep进程脚本
#!/bin/sh while : do n=`mysqladmin processlist -uadmin -p***|grep -i sleep |wc -l` date=`date +%Y%m% ...
- httpclient 怎么带上登录成功后返回的cookie值访问下一页面
我是只很菜很菜的小鸟.刚上班,有这个一个需求.要我抓取别的网站的数据. 我根据用户密码登录一个网站成功后,生成一个cookie值.我已经获取到了.然后要带上这个cookie值进行下一页面的访问 ...
- Linux C 获取系统时间信息
比如获取当前年份: /* 获取当前系统时间 暂时不使用 ; ; time_t now; struct tm *timenow; time(&now); timeno ...
- UTI 唯一类型标识
本文转载至 http://blog.csdn.net/zaitianaoxiang/article/details/6657231 applicationdocumentationtypessys ...
- Session基础知识
Session基础知识 主题 概念 Session的创建 Session的存储机制 Session的失效 参考资料 概念 Session代表一次用户会话.一次用户会话的含义是:从客 ...
- 客户端-服务器通信安全 sign key
API接口签名校验,如何安全保存appsecret? - 知乎 https://www.zhihu.com/question/40855191 要保证一般的客户端-服务器通信安全,可以使用3个密钥. ...
- 基于Mesos和Docker的分布式计算平台
基于Mesos和Docker的分布式计算平台 http://www.csdn.net/article/2015-06-09/2824906