Last active
August 29, 2015 14:14
-
-
Save setchi/b6fe025a9b5f7ae12444 to your computer and use it in GitHub Desktop.
UnityでHTTP通信するクラス
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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); | |
} | |
} | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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