using UnityEngine;
using System.Collections;
using System.Collections.Generic;
using System.IO;
using System.Runtime.Serialization;
using System.Runtime.Serialization.Formatters.Binary;
using System;
namespace Engine.Http
{
public delegate void HandlerResponser(HttpResponse responder);
public delegate void HandlerRequestTimeout(HttpRequest request);
/// http消息
internal class HttpMsg
{
/// Http请求消息头
private static Dictionary MsgHeaders = new Dictionary() { { "Content-Type", "application/x-www-form-urlencoded" } };
/// 消息对象
private WWW mHttp3W;
/// 消息请求参数对象
public HttpRequest mHttpRequest;
/// 是否使用中
public bool IsUseIng = false;
/// 请求是否完成
public bool IsRequestComplete = false;
/// 请求进度,例如进度是10%返回值是10
public int RequestProgress = 0;
/// 响应对象
public HttpResponse mHttpResponse;
/// 响应时间
private int mResponseTime = 0;
private bool mIsTimeout = false;
private Action httpCallBack;//回调函数 dudu add 2020-06-28
/// 开始下载
public HttpMsg() { }
/// 发送消息
public void SendMsg(HttpRequest requestParam, Action httpCallBack = null)
{
//使用中
IsUseIng = true;
//保存请求参数对象
mHttpRequest = requestParam;
this.httpCallBack = httpCallBack;
//创建请求对象 创建后请求已经开始发送
if (mHttpRequest.httpMethod == HttpMethod.POST)
{
//byte[] bytes = ObjectToBytes(mHttpRequest.postData);
mHttp3W = new WWW(mHttpRequest.URL, System.Text.UTF8Encoding.UTF8.GetBytes(mHttpRequest.RequestParamContent), MsgHeaders);
}else
{
mHttp3W = new WWW(mHttpRequest.URLAndParamsForGet);
}
CDebug.Log("http网络请求已发送:" + mHttpRequest.URL + "?"+ (mHttpRequest.httpMethod == HttpMethod.POST));
}
public void SendCallBack()
{
if(httpCallBack != null)
{
httpCallBack.Invoke(mHttpResponse);
}
}
public static byte[] ObjectToBytes(object obj) {
using (MemoryStream ms = new MemoryStream()) {
IFormatter formatter = new BinaryFormatter();
formatter.Serialize(ms, obj);
return ms.GetBuffer();
}
}
/// 帧函数,检查请求是否完成
public void OnUpdate(int nTime)
{
if (mHttp3W == null || IsRequestComplete || mIsTimeout)
{ return; }
mResponseTime += nTime;
if (mHttp3W.isDone)
{
//下载完成后的第二帧修改完成 标记
if (RequestProgress == 100)
{
IsRequestComplete = true;
}
RequestProgress = 100;
if (IsRequestComplete)
{
//创建响应对象
mHttpResponse = HttpResponse.OnCreateResponse(mHttp3W.text, mHttpRequest);
}
}
else
{
RequestProgress = (int)(mHttp3W.progress * 100);
if(mResponseTime >= HttpManager.ResponseOverTimeLimit)
{
mResponseTime = 0;
mIsTimeout = true;
/*if (mHttpRequest.requestTimeout != null)//TODO 请求超时
{
mHttpRequest.requestTimeout(mHttpRequest);
}*/
}
}
}
/// 重置请求对象
public void Reset()
{
IsUseIng = false;
mHttp3W = null;
mHttpRequest.Reset();
mHttpRequest = null;
if(mHttpResponse != null)
mHttpResponse.Reset();
mHttpResponse = null;
RequestProgress = 0;
mResponseTime = 0;
mIsTimeout = false;
IsRequestComplete = false;
}
public float ResponseTime
{
get
{
return mResponseTime;
}
}
public bool IsTimeout
{
get
{
return mIsTimeout;
}
}
}
}