0

HTTPRequest trong Unity

1.Giới thiệu về UnityWebRequest

UnityWebRequest là một module giúp cho các game tạo bởi Unity có thể tương tác được với các web service thông qua HTTPRequest và xử lý các HTTP responses. Đến phiên bản Unity 5.3 thì UnityWebRequest đã hỗ trợ được cho các nên tảng như UnityWebGL, Editor, iOS, Android, Windows Phone 8. Các nền tảng khác mà Unity đã hỗ trợ thì cũng đang được phát triển. Chức năng chính của UnityWebRequest chính:

  • Gửi dữ liệu lên server thông qua UploadHandler
  • Nhận dữ liệu từ server thông qua DownloadHandler
  • Nhận các luồng điều khiển HTTP như điều hướng, xử lý lỗi, ...

Giống với hầu hết các thư viện hỗ trợ việc gửi request khác thì để thực hiện một request thì cần làm các bước chung sau:

  • Khởi tạo đối tượng WebRequest
  • cấu hình cho đối tượng như các việc
    • custom headers
    • cài đặt phương thức
    • cài đặt url
  • Ngoài ra còn có thể truyền dữ liệu hoặc các HTTPform vào đối tượng nếu cần để truyền dữ liệu lên server.
  • Gửi request
  • Nhận dữ liệu trả về từ DownloadHandler hoặc xử lý khi gặp lỗi ...

2.Các phương thức cơ bản của UnityWebRequest

GET:

  • Nhận text hoặc dữ liệu nhị phân đơn giản:

    với phương thức nhận dữ liệu đơn giản từ server là GET thì chúng ta không cần thiết phải có UploadHandler bởi chúng ta không cần truyền dữ liệu nên và chỉ cần 1 đoạn code đơn giản sau chúng ta có thể tạo ra được 1 đối tượng UnityWebRequest để có thể nhận dữ liệu từ server trả về:

using UnityEngine;
using UnityEngine.Experimental.Networking;
using System.Collections;
public class S1TargetScript : MonoBehaviour {
    void Start () {
		StartCoroutine (GetData ());
	}
    IEnumerator GetData() {
		UnityWebRequest getRequest = UnityWebRequest.Get ("http://address.com/example");
		yield return getRequest.Send ();
		if (getRequest.isError) {
			Debug.Log (getRequest.error);
		} else {
			Debug.Log (getRequest.downloadHandler.text);
		}
	}
}
  • download các Texture:

    Ở đây thay vì chúng ta lấy các dữ liệu thông thường bằng phương thức GET thì chúng ta sử dụng phương thức GetTexture được tối ưu cho việc download và lưu trữ texture. Khác với phương thức GET bên trên thì đối tượng UnityWebRequest được thêm một đối tượng DownloadHandlerTexture là một đối tượng DownloadHandler được tối ưu để lưu trữ ảnh.

using UnityEngine;
using UnityEngine.Experimental.Networking;
using System.Collections;
public class S1TargetScript : MonoBehaviour {
    void Start () {
		StartCoroutine (GetTexture ());
	}
    IEnumerator GetTexture() {
		UnityWebRequest getRequest = UnityWebRequest.GetTexture ("http://address.com/example");
		yield return getRequest.Send ();
		if (getRequest.isError) {
			Debug.Log (getRequest.error);
		} else {
			Texture myTexture = ((DownloadHandlerTexture)www.downloadHandler).texture;
		}
	}
}

Hoặc bạn cũng có thể viết hàm GetTexture đơn giản sau:

IEnumerator GetTexture() {
        UnityWebRequest getRequest = UnityWebRequest.GetTexture("http://address.com/example");
        yield return getRequest.Send();
        Texture myTexture = DownloadHandlerTexture.GetContent(getRequest);
    }
  • Download Asset từ server:

    Đối với các asset bundle thì cũng có một đối tượng hander riêng là DownloadHandlerAssetBundle nó có thể extract được asset chúng ta vừa download và decoded cho phép chúng ta truy cập được resource bên trong của các asset.

using UnityEngine;
using UnityEngine.Experimental.Networking;
using System.Collections;
public class S1TargetScript : MonoBehaviour {
    void Start () {
		StartCoroutine (GetAssetBundle ());
	}
    IEnumerator GetAssetBundle() {
		UnityWebRequest getRequest = UnityWebRequest.GetAssetBundle ("http://address.com/example.unity3d");
		yield return getRequest.Send ();
		if (getRequest.isError) {
			Debug.Log (getRequest.error);
		} else {
			AssetBundle bundle = ((DownloadHandlerAssetBundle)getRequest.downloadHandler).assetBundle;
		}
	}
}

Tương tự với GetTexture thì bạn cũng có thể viết phương thức GetAssetBundle đơn giản như sau

IEnumerator GetTexture() {
        UnityWebRequest getRequest = UnityWebRequest.GetAssetBundle("http://address.com/example.unity3d");
        yield return getRequest.Send();

        AssetBundle bundle = DownloadHandlerAssetBundle.GetContent(getRequest);
    }

POST

  • Gửi dữ liệu đơn giản lên server thông qua đối tượng WWWForm. Phương thức được gán 1 đối tượng DownloadHandlerBuffer phù hợp để có thể kiểm soát được được giá trị trả về của server.
IEnumerator upload() {
		WWWForm form = new WWWForm ();
		form.AddField ("myField", "myData");

		UnityWebRequest uploadRequest = UnityWebRequest.Post ("http://address.com/myform", form);
		yield return uploadRequest.Send ();

		if (uploadRequest.isError) {
			Debug.Log (uploadRequest.error);
		} else {
			Debug.Log ("upload complete");
		}
	}
  • Ngoài ra UnityWebRequest còn hỗ trợ multipart cho việc upload nhiều kiểu dữ liệu khác nhau vi dụ đối với data thì có MultipartFormDataSection, đối với file thì có MultipartFormFileSection.
using System.Collections.Generic;
IEnumerator multipart() {
		List<IMultipartFormSection> formData = new List<IMultipartFormSection> ();
		formData.Add (new MultipartFormDataSection ("field1=foo&field2=bar"));
		formData.Add (new MultipartFormFileSection ("my file data", "myfile.txt"));

		UnityWebRequest multipartRequest = UnityWebRequest.Post ("http://address.com/form", formData);
		yield return multipartRequest.Send ();
		if (multipartRequest.isError) {
			Debug.Log (multipartRequest.error);
		} else {
			Debug.Log ("Upload complete");
		}
	}

PUT

  • Tương tự với POST thì chúng ta còn có phương thức PUT với code đơn giản sau:
IEnumerator putUpload() {
		byte[] data = System.Text.Encoding.UTF8.GetBytes ("test data");
		UnityWebRequest putRequest = UnityWebRequest.Put ("http://address.com/upload", data);
		yield return putRequest.Send ();

		if (putRequest.isError) {
			Debug.Log (putRequest.error);
		} else {
			Debug.Log ("Upload complete");
		}
	}

3.Tổng kết

Trên đây là những phương thức cơ bản khá dễ dùng của UnityWebService để hỗ trợ cho chúng ta việc tương tác giữa Unity Game với server. Trên cơ sở các phương thức có sẵn này để chúng ta có thể từng bước xây dựng lên các tương tác cao hơn trong game multiplayer.


All rights reserved

Viblo
Hãy đăng ký một tài khoản Viblo để nhận được nhiều bài viết thú vị hơn.
Đăng kí