1. 程式人生 > >Unity Http 訊息傳送與接受

Unity Http 訊息傳送與接受

參考:

https://blog.csdn.net/mseol/article/details/54138762

https://blog.csdn.net/h570768995/article/details/50386935

https://stackoverflow.com/questions/16910788/unity3d-post-a-json-to-asp-net-mvc-4-web-api

圖片和base64互轉https://blog.csdn.net/jiangyangll/article/details/80566330

C# int和byte之間的互轉https://blog.csdn.net/zuoyefeng1990/article/details/71480499

短連結使用WWW或UnityWebRequest傳送請求

WWW的建構函式有3種:

1.只發送http請求,不帶引數

public WWW(string url);

2.使用表單傳送帶資料的http請求

public WWW(string url, WWWForm form);

public WWW(string url, byte[] postData);// 這個資料頭預設好像是表單

3.使用json傳送帶資料的http請求

public WWW(string url, byte[] postData, Dictionary<string, string> headers);

json轉byte[] 程式碼:

System.Text.Encoding.UTF8.GetBytes(json.ToString())

json資料表頭:

Dictionary<string, string> headers = new Dictionary<string, string>();
headers.Add("Content-Type", "application/json");

 

附1:

long資料轉byte[]

public static byte[] longToBytes(long value)
{
    byte[] src = new byte[8];
    src[7] = (byte)((value >> 56) & 0xFF);
    src[6] = (byte)((value >> 48) & 0xFF);
    src[5] = (byte)((value >> 40) & 0xFF);
    src[4] = (byte)((value >> 32) & 0xFF);
    src[3] = (byte)((value >> 24) & 0xFF);
    src[2] = (byte)((value >> 16) & 0xFF);
    src[1] = (byte)((value >> 8) & 0xFF);
    src[0] = (byte)(value & 0xFF);
    return src;
}

附2:

返回的資料解析成Json(使用SimpleJson)

object obj = null;
bool success = SimpleJson.SimpleJson.TryDeserializeObject(www.text, out obj);

if (!success || obj == null)
{
     Debug.LogError("Network Error: Http Response is not Json!");
     yield break;
}

JsonObject args = obj as JsonObject;

附3:

base64圖片資料生成圖片


	public static void Base64ToImg(Image imgComponent, string base64, int width, int height)
	{
		byte[] bytes = System.Convert.FromBase64String(base64);
		Texture2D tex2D = new Texture2D(width, height);
		tex2D.LoadImage(bytes);
		Sprite s = Sprite.Create(tex2D, new Rect(0, 0, tex2D.width, tex2D.height), new Vector2(0.5f, 0.5f));
		imgComponent.sprite = s;
		Resources.UnloadUnusedAssets();
	}

 

其他