Unity/Csharp/Request
提供: 初心者エンジニアの簡易メモ
目次
Httpリクエストサンプル
以下delegateを使ったhttpリクエストサンプルコード
- WebHttpRequest.cs
using System.Collections; using UnityEngine; using UnityEngine.Networking; public class WebHttpRequest : MonoBehaviour { string text = ""; public bool errorFlag = false; public enum ResponseType { Success, Failure, NetworkError } public delegate void CustomCallback(ResponseType responseType); private CustomCallback callbacks; public void AddCallback(CustomCallback callback) { callbacks += callback; } 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.isNetworkError) { errorFlag = true; if (callbacks != null) { callbacks(ResponseType.NetworkError); } } else { if (request.responseCode == 200) { text = request.downloadHandler.text; if (callbacks != null) { callbacks(ResponseType.Success); } } else { errorFlag = true; if (callbacks != null) { callbacks(ResponseType.Failure); } } } } public string GetBody() { return text; } public void Reset() { text = ""; errorFlag = false; } }
呼び出し元
- NewBehaviourScript.cs
public class NewBehaviourScript : MonoBehaviour { WebHttpRequest request; // http送信 void Start () { const string uri = "http://raw.githubusercontent.com/nlohmann/json/develop/test/data/json.org/1.json"; string param1 = "value1"; param1 = WWW.EscapeURL(param1); string query = "?hoge=" + param1; string url = uri + query; GameObject gameObj = new GameObject(); request = gameObj.AddComponent<WebHttpRequest>(); request.AddCallback(OnResponse); request.Exec(url); Debug.Log("request=" + url); } // httpのresponse受信 public void OnResponse(WebHttpRequest.ResponseType responseType) { Debug.Log("OnResponse=" + responseType); if (request) { if (responseType.Equals(WebHttpRequest.ResponseType.Success)) { Debug.Log("body=" + request.GetBody()); } else if (responseType.Equals(WebHttpRequest.ResponseType.Failure)) { Debug.Log("errorFlag=" + request.errorFlag); } else if (responseType.Equals(WebHttpRequest.ResponseType.NetworkError)) { Debug.Log("NetworkError" + request.errorFlag); } request.Reset(); } } }
Httpリクエストサンプル(これはDelegateを使ってないダメな例)
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) { text = request.downloadHandler.text; 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 ("")) { // 処理 request.Reset (); } else if (request.errorFlag) { request.errorFlag = false; } } }
http通信許可
android
android9でhttp通信ができなくなってる。
取り急ぎhttp通信を対応したい場合 AndroidManifest.xmlのapplicationに以下属性追加
android:usesCleartextTraffic="true"
https://ameblo.jp/znky/entry-12459683348.html
ios
- unity/build setting/ios/other setting
- Allow downloads over HTTPをチェック
チェックをつけると以下警告が出る
You are using download over http. Currently Unity adds NSAllowsArbitraryLoads to Info.plist to simplify transition, but it will be removed soon. Please consider updating to https.
それでも、http通信時、以下が出る時
The resource could not be loaded because the App Transport Security policy requires the use of a secure connection.
info.plistへ以下を追加
<key>NSAppTransportSecurity</key> <dict> <key>NSAllowsArbitraryLoads</key> <true /> <key>NSAllowsArbitraryLoadsInWebContent</key> <true /> <key>NSExceptionDomains</key> <dict> <key>project1.example.net</key> <dict> <key>NSIncludesSubdomains</key> <true /> <key>NSTemporaryExceptionAllowsInsecureHTTPLoads</key> <true /> </dict> </dict>
project1.example.netは適宜変更
参考:https://clevertap.com/blog/developing-for-ios9-app-transport-security/
補足
unityのiosの設定のAllow downloads over HTTPの下にあるSizeに1を入力しSchemaに、接続するドメイン(project1.example.netなど)を追加しても、以下が追加されるだけで、NSExceptionDomainsではないので、機能しない。
<key>CFBundleURLTypes</key> <array> <dict> <key>CFBundleURLName</key> <string></string> <key>CFBundleURLSchemes</key> <array> <string>project1.example.net</string> </array> </dict> </array>