HTTP interface Access Class

Source: Internet
Author: User

Using Unityengine;
Using System.Collections;
Using System;
Using System.Text;
Using Litjson;
Using System.Collections.Generic;
Using Networkmessages;
Using System.Reflection;

<summary>
HTTP interface Access Class
</summary>
public class Webaccess:monobehaviour
{
<summary>
Relationship between interface classification and background service Base site mapping
</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>
Dictionary of the name of the HTTP interface that returns the result type corresponding to the interface
</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> ();
Add the return result type of all the HTTP interfaces used
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>
Executing the HTTP interface
</summary>
<param name= "Parameters" > interface Required Parameters </param>
<param name= "onsuccess" > Interface call is successful when callback </param>
<param name= "Onfail" > Callback when the interface call fails </param>
<typeparam name= "TResult" > Return result type for this HTTP interface </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>
To access the HTTP interface in a co-process manner
</summary>
<param name= "Parameters" > interface Required Parameters </param>
<param name= "Resulttype" > return result type </param>
<param name= "onsuccess" > Interface call is successful when callback </param>
<param name= "Onfail" > Callback when the interface call fails </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 the progress does not move for a long time, accumulate this time, do time-out processing.
if (www.progress! = progress)
{
Reset timeout timed to 0 if progress is changed
Time = 0f;
progress = www.progress;
}
Time + = Time.deltatime;
if (Time > Timeout)
{
Break
}
yield return null;
}
Try
{
if (Time > Timeout)
{
Debug.logerror ("HTTP Interface Access timeout");
Safelyinvokeonfailcallback (Onfail, New Webapierror ("HTTP Interface Access timeout"));
}
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>
To safely invoke a successful callback method
</summary>
void Safelyinvokeonsuccesscallback (action<webapiresult> onsuccess, webapiresult result)
{
if (onsuccess! = null)
{
Package callback calls can be avoided because the exception of the callback itself is judged to be a RUNAPI error.
Try
{
Onsuccess (result);
}
catch (Exception e)
{
Debug.logexception (e);
}
}
}

<summary>
To safely invoke the failed callback method
</summary>
void Safelyinvokeonfailcallback (action<webapierror> onfail, webapierror error)
{
if (onfail! = null)
{
Package callback calls can be avoided because the exception of the callback itself is judged to be a RUNAPI error.
Try
{
Onfail (Error);
}
catch (Exception e)
{
Debug.logexception (e);
}
}
}

}

HTTP interface Access Class

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.