facebook twitter hatena line email

「Unity/Csharp/Request」の版間の差分

提供: 初心者エンジニアの簡易メモ
移動: 案内検索
(Httpリクエストサンプル)
(Httpリクエストサンプル)
行1: 行1:
 
==Httpリクエストサンプル==
 
==Httpリクエストサンプル==
  public class ComScript : MonoBehaviour {
+
public class WebRequest : MonoBehaviour {
    public void Exec () {
+
string text = "";
      string url = "ttp://hogehoge.com/api?name1="
+
public bool errorFlag = false;
      string param = "value1";
+
public void Exec (string url) {
      url += WWW.EscapeURL (param);
+
text = "";
      StartCoroutine(Get (url));
+
errorFlag = false;
    }
+
StartCoroutine(Get (url));
 +
}
 
     public IEnumerator Get (string url) {
 
     public IEnumerator Get (string url) {
 
       var request = new UnityWebRequest();
 
       var request = new UnityWebRequest();
行25: 行26:
  
 
呼び出し側
 
呼び出し側
 +
const string uri = "ttp://hogehoge.com/api?param1=";
 +
string param1 = "value1";
 +
param1 = WWW.EscapeURL (param1);
 +
string url = uri + sfen;
 
  GameObject gameObj = new GameObject();
 
  GameObject gameObj = new GameObject();
  ComScript com = gameObj.AddComponent<ComScript>();
+
  WebRequest request = gameObj.AddComponent<WebRequest>();
  com.Exec ();
+
  request.Exec ();

2017年11月9日 (木) 09:27時点における版

Httpリクエストサンプル

public class WebRequest : 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);
       }
     }
   }
 }

呼び出し側

const string uri = "ttp://hogehoge.com/api?param1=";
string param1 = "value1";
param1 = WWW.EscapeURL (param1);
string url = uri + sfen;
GameObject gameObj = new GameObject();
WebRequest request = gameObj.AddComponent<WebRequest>();
request.Exec ();