ThreadHttpWebRequest
using UnityEngine;
using System.Collections;
using System;
using System.Net;
using System.IO;
using UnityEngine.UI;
public class ThreadHttpWebRequest
{
public class ThreadHttpGet
{
public string name = "ThreadHttpGet";
public string url;
public Action<bool, string> callback;
public int timeout = 10;
public bool isEnd = false;
public bool isSuccess = false;
public string result = null;
public IEnumerator Coroutine()
{
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
request.Timeout = 10;
//异步请求
IAsyncResult asyncResult = request.BeginGetResponse(requestCompleted, request);
Log("Main", "任务开始");
float t = 0;
while(!isEnd)
{
yield return new WaitForEndOfFrame();
t += Time.unscaledDeltaTime;
if (t > timeout)
{
try
{
request.EndGetResponse(asyncResult);
}
catch(Exception e)
{
Log("Main", "请求超时 e=" + e);
}
isEnd = true;
isSuccess = false;
result = "请求超时 timeout=" + timeout + " t=" + t;
}
}
Log("Main", "IsCompleted=" + asyncResult.IsCompleted);
if (callback != null)
{
callback(isSuccess, result);
}
}
//回调函数 此方法不是在Main线程运行
private void requestCompleted(IAsyncResult asyncResult)
{
if (asyncResult == null || asyncResult.AsyncState==null)
{
Log("Callback", "回调失败");
isEnd = true;
isSuccess = false;
result = "回调失败";
return;
}
HttpWebRequest hwr = asyncResult.AsyncState as HttpWebRequest;
HttpWebResponse response = (HttpWebResponse)hwr.EndGetResponse(asyncResult);
StreamReader sr = new StreamReader(response.GetResponseStream());
string str = sr.ReadToEnd();
isEnd = true;
isSuccess = true;
result = str;
Log("Callback","返回流长度:" + str.Length + " " + str);
}
private void Log(string threadName, string msg)
{
Debug.LogFormat("{1} {0} {4} [{2}] {3}", name, time, threadName, msg, url);
}
private void Error(string threadName, string msg)
{
Debug.LogErrorFormat("{1} {0} {4} [{2}] {3}", name, time, threadName, msg, url);
}
public string time
{
get
{
return DateTime.Now.ToString("mm:ss:ffff");
}
}
}
public class ThreadHttpUpload
{
public string name = "ThreadHttpUpload";
public string url;
public Action<bool, string> callback;
public bool isEnd = false;
public bool isSuccess = false;
public string result = null;
public IEnumerator Coroutine(byte[] bindata, CookieContainer cookie, int timeout = 10)
{
HttpWebRequest request = null;
HttpWebRequest req = null;
Stream myRequestStream = null;
HttpWebResponse wr = null;
request = (HttpWebRequest)WebRequest.Create(url);
request.Method = "POST";
request.ContentType = "application/octet-stream";
request.ContentLength = bindata.Length;
request.Timeout = timeout;
if(cookie != null) request.CookieContainer = cookie;
try
{
request.BeginGetRequestStream((IAsyncResult result)=>
{
if (!result.IsCompleted)
{
Debug.LogError("上传 写入数据失败");
return;
}
myRequestStream = request.EndGetRequestStream(result);
myRequestStream.Write(bindata, 0, bindata.Length);
}, request);
}
catch (Exception e)
{
Error("Main", "上传 写入数据异常 e=" + e);
isEnd = true;
isSuccess = false;
result = "上传 写入数据异常 e=" + e;
if (callback != null)
{
callback(isSuccess, result);
}
yield break;
}
//异步请求
IAsyncResult asyncResult = request.BeginGetResponse(requestCompleted, request);
Log("Main", "任务开始");
float t = 0;
while(!isEnd)
{
yield return new WaitForEndOfFrame();
t += Time.unscaledDeltaTime;
if (t > timeout)
{
try
{
request.EndGetResponse(asyncResult);
}
catch(Exception e)
{
Log("Main", "请求超时 e=" + e);
}
isEnd = true;
isSuccess = false;
result = "请求超时 timeout=" + timeout + " t=" + t;
}
}
Log("Main", "IsCompleted=" + asyncResult.IsCompleted);
if (callback != null)
{
callback(isSuccess, result);
}
}
//回调函数 此方法不是在Main线程运行
private void requestCompleted(IAsyncResult asyncResult)
{
if (asyncResult == null || asyncResult.AsyncState==null)
{
Log("Callback", "回调失败");
isEnd = true;
isSuccess = false;
result = "回调失败";
return;
}
HttpWebRequest hwr = asyncResult.AsyncState as HttpWebRequest;
HttpWebResponse response = (HttpWebResponse)hwr.EndGetResponse(asyncResult);
StreamReader sr = new StreamReader(response.GetResponseStream());
string str = sr.ReadToEnd();
isEnd = true;
isSuccess = true;
result = str;
Log("Callback","返回流长度:" + str.Length + " " + str);
}
private void Log(string threadName, string msg)
{
Debug.LogFormat("{1} {0} {4} [{2}] {3}", name, time, threadName, msg, url);
}
private void Error(string threadName, string msg)
{
Debug.LogErrorFormat("{1} {0} {4} [{2}] {3}", name, time, threadName, msg, url);
}
public string time
{
get
{
return DateTime.Now.ToString("mm:ss:ffff");
}
}
}
public static ThreadHttpGet StartGet(string url, Action<bool, string> callback, MonoBehaviour mono, int timeout = 10, string name = null)
{
ThreadHttpGet thread = new ThreadHttpGet();
thread.name = string.IsNullOrEmpty(name) ? "ThreadHttpGet" : name;
thread.url = url;
thread.callback = callback;
thread.timeout = timeout;
mono.StartCoroutine(thread.Coroutine());
return thread;
}
public static ThreadHttpUpload StartUpload(string url, CookieContainer cookie , byte[] bindata, Action<bool, string> callback, MonoBehaviour mono, int timeout = 10, string name = null)
{
ThreadHttpUpload thread = new ThreadHttpUpload();
thread.name = string.IsNullOrEmpty(name) ? "ThreadHttpUpload" : name;
thread.url = url;
thread.callback = callback;
mono.StartCoroutine(thread.Coroutine(bindata, cookie, timeout));
return thread;
}
}
ThreadHttpWebRequest
using UnityEngine;
using System.Collections;
using System;
using System.Net;
using System.IO;
using UnityEngine.UI;
public class TestThreadHttpWebRequest : MonoBehaviour {
public void OnGUI()
{
GUI.Label(new Rect(Screen.width - 100, 20, 100, 50), Time.frameCount + "");
if (GUI.Button(new Rect(10, 10, 100, 50), "Get"))
{
ThreadHttpWebRequest.StartGet(url, OnEnd, this);
}
if (GUI.Button(new Rect(200, 10, 100, 50), "Upload"))
{
string urlpath = "http://192.168.1.21:8080/video_upload?type=6";
byte[] data = File.ReadAllBytes("Assets/StreamingAssets/test_WarEnterData.json");
ThreadHttpWebRequest.StartUpload(urlpath, VideoCookie(urlpath, 1, 0, null), data, OnEnd, this);
}
if (GUI.Button(new Rect(200, 60, 100, 50), "GetMyFile"))
{
string urlpath = "http://192.168.1.21:8080/video_get?roleid=0&videoid=1&leagueId=0&type=6";
ThreadHttpWebRequest.StartGet(urlpath, OnEnd, this);
}
GUI.TextArea(new Rect(10, Screen.height - 300, Screen.width, 280), result);
}
public void OnEnd(bool isSuccess, string result)
{
this.isSucces = isSucces;
this.result = result;
if (text != null)
text.text = result;
}
public string url = "http://blog.ihaiu.com";
public string isSucces;
public string result = "";
public Text text;
private CookieContainer VideoCookie(string url, int videoId, int leagueId, string sessionId = null)
{
if (string.IsNullOrEmpty(sessionId))
{
sessionId = "0";
}
Uri target = new Uri(url);
CookieContainer videoCookie = new CookieContainer();
videoCookie.Add(new Cookie("sessionId", sessionId){Domain=target.Host} );
videoCookie.Add(new Cookie("videoId", videoId.ToString()){Domain=target.Host} );
videoCookie.Add(new Cookie("leagueId", leagueId.ToString()) { Domain = target.Host });
return videoCookie;
}
}