求大神把下面這個代碼改成 UnityWebRequest 請求
IEnumerator Get(string url, string auth, string json)
{
Dictionary<string,string> header = new Dictionary<string, string>();
byte[] postBytes;
header.Add("Content-Type", "application/json");//添加header
if(auth != null)
{
header.Add("Authorization",auth);
}
if(json != null)
{
//POST
//將資料轉換成json資料流
postBytes = System.Text.Encoding.UTF8.GetBytes(json);
}
else
{
//GET
//此案例不需要json資料所以為null
postBytes=null;
}
WWW www = new WWW (url,postBytes,m_dir);
yield return www;
if (www.error != null)
{
Debug.Log("error is :"+ www.error);
}
else
{
Debug.Log("request result :" + www.text);
}
}
uj5u.com熱心網友回復:
額,這個查一下官方檔案就可以了呀uj5u.com熱心網友回復:
using System;using System.Collections;
using System.IO;
using UnityEngine.Networking;
public class HttpDownLoad
{
public float progress { get; private set; }
public bool isDone { get; private set; }
private bool isStop;
public IEnumerator Start(string url, string filePath, Action callBack)
{
var headRequest = UnityWebRequest.Head(url);
yield return headRequest.SendWebRequest();
var totalLength = long.Parse(headRequest.GetResponseHeader("Content-Length"));
var dirPath = Path.GetDirectoryName(filePath);
if (!Directory.Exists(dirPath))
{
Directory.CreateDirectory(dirPath);
}
using (var fs = new FileStream(filePath, FileMode.OpenOrCreate, FileAccess.Write))
{
var fileLength = fs.Length;
if (fileLength < totalLength)
{
fs.Seek(fileLength, SeekOrigin.Begin);
var request = UnityWebRequest.Get(url);
request.SetRequestHeader("Range", "bytes=" + fileLength + "-" + totalLength);
request.SendWebRequest();
var index = 0;
while (!request.isDone)
{
if (isStop) break;
yield return null;
var buff = request.downloadHandler.data;
if (buff != null)
{
var length = buff.Length - index;
fs.Write(buff, index, length);
index += length;
fileLength += length;
if (fileLength == totalLength)
{
progress = 1f;
}
else
{
progress = fileLength / (float) totalLength;
}
}
}
}
else
{
progress = 1f;
}
fs.Close();
fs.Dispose();
}
if (progress >= 1f)
{
isDone = true;
if (callBack != null)
{
callBack();
}
}
}
public void Stop()
{
isStop = true;
}
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/qita/23870.html
標籤:Unity3D
