码迷,mamicode.com
首页 > Web开发 > 详细

HTTP接口访问类

时间:2017-12-06 17:52:31      阅读:184      评论:0      收藏:0      [点我收藏+]

标签:llb   sem   red   sum   oob   ima   run   float   计时   

using UnityEngine;
using System.Collections;
using System;
using System.Text;
using LitJson;
using System.Collections.Generic;
using NetworkMessages;
using System.Reflection;

/// <summary>
/// HTTP接口访问类
/// </summary>
public class WebAccess : MonoBehaviour
{
/// <summary>
/// 接口分类与后台服务基地址映射关系
/// </summary>
private static Dictionary<string, string> apiTypeToServerBaseUrlMap;

private static void InitializeApiTypeToServerUrlMap()
{
apiTypeToServerBaseUrlMap = new Dictionary<string, string>
{
{ "account", "http://192.168.0.75:8990/" },
{ "logic", "http://192.168.0.75:9601/" },
{ "PENDING", "http://192.168.0.75:11001/" },
};
}
private const float timeout = 3f;
static WebAccess instance;

public static WebAccess Instance
{
get
{
if (instance == null)
{
InitializeApiMaps();
InitializeApiTypeToServerUrlMap();
GameObject go = new GameObject("WebAccess");
instance = go.AddComponent<WebAccess>();
DontDestroyOnLoad(go);
return instance;
}
else
{
return instance;
}
}
}

private string token;
private Dictionary<string, string> headersToSend = new Dictionary<string, string>();

public string Token
{
get
{
return token;
}
set
{
token = value;
Debug.Log("set token to " + value);
headersToSend["Authorization"] = token;
}
}

/// <summary>
/// HTTP接口的返回结果类型与该接口对应的名称的字典
/// </summary>
static Dictionary<Type, string> apiNameMaps = null;
static Dictionary<Type, string> apiTypeMaps = null;

static void InitializeApiMaps()
{
apiNameMaps = new Dictionary<Type, string>();
apiTypeMaps = new Dictionary<Type, string>();
// 添加所有用到的HTTP接口的返回结果类型
Assembly current = Assembly.GetExecutingAssembly();
Type[] allTypes = current.GetTypes();
for (int i = 0; i < allTypes.Length; i++)
{
Type type = allTypes[i];
if (type.IsDefined(typeof(WebApiResultAttribute), false))
{
WebApiResultAttribute attr = type.GetCustomAttributes(typeof(WebApiResultAttribute), false)[0] as WebApiResultAttribute;
apiNameMaps.Add(type, attr.ApiName);
apiTypeMaps.Add(type, attr.ApiType);
}
}
Debug.Log("registered Web-API count: " + apiNameMaps.Count);
}

void OnDestroy()
{
instance = null;
if (apiNameMaps != null)
{
apiNameMaps.Clear();
apiNameMaps = null;
}
if (apiTypeMaps != null)
{
apiTypeMaps.Clear();
apiTypeMaps = null;
}
}

string GetApiUrlByType(Type type)
{
string apiType = apiTypeMaps[type];
string apiName = apiNameMaps[type];
return apiTypeToServerBaseUrlMap[apiType] + apiName;
}

/// <summary>
/// 执行HTTP接口
/// </summary>
/// <param name="parameters">接口所需的参数</param>
/// <param name="onSuccess">接口调用成功时回调</param>
/// <param name="onFail">接口调用失败时的回调</param>
/// <typeparam name="TResult">该HTTP接口的返回结果类型</typeparam>
public void RunAPI<TResult>(WebApiParameter parameters, Action<WebApiResult> onSuccess, Action<WebApiError> onFail) where TResult : WebApiResult
{
DialogTipsCtrl.Instance.BeginWait();
StartCoroutine(GetData(parameters, typeof(TResult), onSuccess, onFail));
}

/// <summary>
/// 以协程方式访问HTTP接口
/// </summary>
/// <param name="parameters">接口所需的参数</param>
/// <param name="resultType">返回结果类型</param>
/// <param name="onSuccess">接口调用成功时回调</param>
/// <param name="onFail">接口调用失败时的回调</param>
IEnumerator GetData(WebApiParameter parameters, Type resultType, Action<WebApiResult> onSuccess, Action<WebApiError> onFail)
{
string json = JsonMapper.ToJson(parameters);
string encrypted = Web.Networking.AesBase64Encrypt.Encrypt(json);
byte[] rawData = Encoding.UTF8.GetBytes(encrypted);
string fullUrl = GetApiUrlByType(resultType);
Debug.Log("accessing " + fullUrl + " with parameters: " + json + " with rawdata: " + encrypted);
WWW www = new WWW(fullUrl, rawData, headersToSend);
float time = 0f;
float progress = 0f;
while (string.IsNullOrEmpty(www.error) && !www.isDone)
{
// 如果进度长时间不动,就累积这个时间,做超时处理。
if (www.progress != progress)
{
// 如果进度变化,重置超时计时为0
time = 0f;
progress = www.progress;
}
time += Time.deltaTime;
if (time > timeout)
{
break;
}
yield return null;
}
try
{
if (time > timeout)
{
Debug.LogError("HTTP接口访问超时");
SafelyInvokeOnFailCallback(onFail, new WebApiError("HTTP接口访问超时"));
}
else if (string.IsNullOrEmpty(www.error))
{
string webResult = www.text;
Debug.Log("server reply: " + www.text);
string decrypted = Web.Networking.AesBase64Encrypt.Decrypt(webResult);
Debug.Log("decrypted server reply: " + decrypted);
object obj = JsonMapper.ToObject(decrypted, resultType);
WebApiResult result = (WebApiResult)obj;
if (result.result == 0)
{
SafelyInvokeOnSuccessCallback(onSuccess, result);
}
else
{
SafelyInvokeOnFailCallback(onFail, new WebApiError(result.result));
}
}
else
{
SafelyInvokeOnFailCallback(onFail, new WebApiError(www.error));
}
}
catch (Exception e)
{
Debug.LogException(e);
SafelyInvokeOnFailCallback(onFail, new WebApiError(e));
}
finally
{
DialogTipsCtrl.Instance.EndWait();
}
}

/// <summary>
/// 安全地调用成功回调方法
/// </summary>
void SafelyInvokeOnSuccessCallback(Action<WebApiResult> onSuccess, WebApiResult result)
{
if (onSuccess != null)
{
// 包裹回调调用,可以避免因为回调本身的异常被判定为 RunAPI 的错误。
try
{
onSuccess(result);
}
catch (Exception e)
{
Debug.LogException(e);
}
}
}

/// <summary>
/// 安全地调用失败回调方法
/// </summary>
void SafelyInvokeOnFailCallback(Action<WebApiError> onFail, WebApiError error)
{
if (onFail != null)
{
// 包裹回调调用,可以避免因为回调本身的异常被判定为 RunAPI 的错误。
try
{
onFail(error);
}
catch (Exception e)
{
Debug.LogException(e);
}
}
}

}

HTTP接口访问类

标签:llb   sem   red   sum   oob   ima   run   float   计时   

原文地址:http://www.cnblogs.com/0315cz/p/7993312.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!