Unity3D 通过Get与Post方式与服务器端进行交互

原文地址:http://www.omuying.com/article/151.aspx

做游戏,基本上都避免不了与服务器端交互,与服务器端交互的方式也有几种,总结起来就是长连接模式(Socket)与短链接模式(Http),由于通常都是使用 Http 这种方式,所以抽象出了 HttpHelper。?

HttpHelper 代码如下:
using System;
using System.Text;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class HttpHelper
{
	private static IList poolItemList = new List ();
	public static void Request(string url, string method, Dictionary formData, Action callback, string responseType)
	{
		HttpHelperItem httpHelperItem = GetOrCreateItem ();
		if(method == MethodTypeInfo.GET)
		{
			httpHelperItem.Request(CreateGetData(url, formData), null, callback, responseType);
		}
		else
		{
			httpHelperItem.Request(url, CreatePostData(formData), callback, responseType);
		}
	}

	private static HttpHelperItem GetOrCreateItem()
	{
		foreach(HttpHelperItem item in poolItemList)
		{
			if(item.isDone) return item;
		}

		GameObject httpHelperObject = new GameObject ();
		httpHelperObject.name = "HttpHelperItem";
		HttpHelperItem httpHelperItem = httpHelperObject.AddComponent ();
		poolItemList.Add (httpHelperItem);
		return httpHelperItem;
	}

	protected static string CreateGetData(string url, Dictionary formData)
	{
		StringBuilder stringBuilder = new StringBuilder ();
		if(formData != null && formData.Count > 0)
		{
			foreach(KeyValuePair keyValuePair in formData)
			{
				stringBuilder.Append(keyValuePair.Key);
				stringBuilder.Append("=");
				stringBuilder.Append(keyValuePair.Value.ToString());
				stringBuilder.Append("&");
			}
		}
		if(url.IndexOf("?") == -1)
		{
			url += "?";
		}else
		{
			url += "&";
		}
		url += stringBuilder.ToString ().TrimEnd (new char[]{'&'});
		return url;
	}

	protected static WWWForm CreatePostData(Dictionary formData)
	{
		WWWForm form = new WWWForm ();
		if(formData != null && formData.Count > 0)
		{
			foreach(KeyValuePair keyValuePair in formData)
			{
				if(keyValuePair.Value is byte[])
				{
					form.AddBinaryData(keyValuePair.Key, keyValuePair.Value as byte[]);
				}else
				{
					form.AddField(keyValuePair.Key, keyValuePair.Value.ToString());
				}
			}
		}
		return form;
	}
}
public class MethodTypeInfo
{
	public static readonly string GET  = "get";
	public static readonly string POST  = "post";
}
public class ResponseTypeInfo
{
	public static readonly string TEXT = "text";
	public static readonly string BYTE = "byte";
}
public class HttpHelperItem : MonoBehaviour
{
	private Action callback;
	private string responseType;
        private string url;
        private string formData;

	public bool isDone;

	public void Request(string url, WWWForm formData, Action callback, string responseType)
	{
		this.callback = callback;
		this.responseType = responseType;
                this.url = url;
                this.formData = formData;

		this.isDone = false;
		
		this.StartCoroutine ("StartRequest");
	}

	private IEnumerator StartRequest(string url, WWWForm formData)
	{
		WWW www = null;
		if(formData == null)
		{
			www = new WWW (url);
		}else
		{
			www = new WWW(url, formData);
		}
		yield return www;
		if(www.isDone && string.IsNullOrEmpty(www.error))
		{
			if(this.responseType == ResponseTypeInfo.BYTE)
			{
				if(this.callback != null) this.callback(www.bytes);
			}else if(this.responseType == ResponseTypeInfo.TEXT)
			{
				if(this.callback != null) this.callback(www.text);
			}
		}
		else
		{
			if(this.callback != null) this.callback("error");
		}
		www.Dispose ();
		this.StopCoroutine ("StartRequest");
		this.isDone = true;
	}
}
使用如下:
using UnityEngine;
using System.Collections.Generic;

public class Test : MonoBehaviour 
{
	void Start () 
	{
		Dictionary dict = new Dictionary ();
		dict.Add ("user", "user1");
		dict.Add ("password", "123456");

		HttpHelper.Request ("http://192.168.1.90:8081/default.aspx", MethodTypeInfo.POST, dict, delegate(object obj) {
			Debug.Log(obj.ToString());
		}, ResponseTypeInfo.TEXT);
	}
}



服务器端代码如下:
public partial class _default : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
        if(!IsPostBack)
        {
            if (Request["user"] != null && Request["password"] != null)
            {
                Response.Write("user:" + Request["user"].ToString() + ",password:" + Request["password"].ToString());
            }
        }
    }
}


你可能感兴趣的:(Unity3D 通过Get与Post方式与服务器端进行交互)