Skip to content

Instantly share code, notes, and snippets.

@setchi
Last active August 29, 2015 14:14
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save setchi/b6fe025a9b5f7ae12444 to your computer and use it in GitHub Desktop.
Save setchi/b6fe025a9b5f7ae12444 to your computer and use it in GitHub Desktop.
UnityでHTTP通信するクラス
using UnityEngine;
using System;
using System.Collections;
using System.Collections.Generic;
public class HTTP : MonoBehaviour {
private static HTTP instance;
// Singleton
private HTTP () {}
static HTTP Instance {
get {
if( instance == null ) {
GameObject go = new GameObject("HTTPSingleton");
instance = go.AddComponent<HTTP>();
}
return instance;
}
}
public static WWW Get(string url, Action<WWW> onSuccess, Action<WWW> onError = null) {
WWW www = new WWW (url);
Instance.StartCoroutine (Instance.WaitForRequest (www, onSuccess, onError));
return www;
}
public static WWW Post(string url, Dictionary<string, string> postParams, Action<WWW> onSuccess, Action<WWW> onError = null) {
WWWForm form = new WWWForm();
foreach (var param in postParams) {
form.AddField(param.Key, param.Value);
}
WWW www = new WWW(url, form);
Instance.StartCoroutine(Instance.WaitForRequest(www, onSuccess, onError));
return www;
}
IEnumerator WaitForRequest(WWW www, Action<WWW> onSuccess, Action<WWW> onError) {
yield return www;
// check for errors
if (string.IsNullOrEmpty(www.error)) {
Debug.Log("WWW Ok!: " + www.text);
onSuccess(www);
} else {
Debug.Log("WWW Error: "+ www.error);
if (onError != null)
onError(www);
}
}
}
// using System;
// using System.Collections.Generic;
// GET
HTTP.Get("http://example.com/", www => {
Debug.Log(www.text);
}, www => {
// on error
Debug.Log(www.error);
});
// POST
var form = new Dictionary<string, string>();
form.Add("param1", "data1");
form.Add("param2", "data2");
HTTP.Post("http://example.com/", form, www => {
Debug.Log(www.text);
}, www => {
// on error
Debug.Log(www.error);
})
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment