「Unity/Csharp/Request」の版間の差分
提供: 初心者エンジニアの簡易メモ
(→Httpリクエストサンプル) |
(→Httpリクエストサンプル) |
||
行45: | 行45: | ||
GameObject gameObj = new GameObject(); | GameObject gameObj = new GameObject(); | ||
WebHttpRequest request = gameObj.AddComponent<WebHttpRequest>(); | WebHttpRequest request = gameObj.AddComponent<WebHttpRequest>(); | ||
− | request.Exec (); | + | request.Exec (url); |
呼び出し側で受信チェック | 呼び出し側で受信チェック |
2017年11月9日 (木) 10:08時点における版
Httpリクエストサンプル
using System.Collections; using System.Collections.Generic; using UnityEngine; using UnityEngine.UI; using System.Collections; using UnityEngine.Networking; public class WebHttpRequest : MonoBehaviour { string text = ""; public bool errorFlag = false; public void Exec (string url) { text = ""; errorFlag = false; StartCoroutine(Get (url)); } public IEnumerator Get (string url) { var request = new UnityWebRequest(); request.downloadHandler = new DownloadHandlerBuffer(); request.url = url; request.SetRequestHeader("Content-Type", "application/json; charset=UTF-8"); request.method = UnityWebRequest.kHttpVerbGET; yield return request.Send(); if (request.isError) { Debug.Log(request.error); } else { if (request.responseCode == 200) { Debug.Log(request.downloadHandler.text); } } } public string GetBody() { return text; } public void Reset() { text = ""; errorFlag = false; } }
呼び出し側
const string uri = "ttp://hogehoge.com/api?param1="; string param1 = "value1"; param1 = WWW.EscapeURL (param1); string url = uri + param1; GameObject gameObj = new GameObject(); WebHttpRequest request = gameObj.AddComponent<WebHttpRequest>(); request.Exec (url);
呼び出し側で受信チェック
void Update () { if (request) { if (!request.GetBody ().Equals ("")) { } else if (request.errorFlag) { request.errorFlag = false; } } }