84
83

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

UnityでGET, POST通信(+JSON)

Last updated at Posted at 2014-08-07

LitJsonが必要です。

TestWWW.cs
using UnityEngine;
using System.Text;
using System.Collections;
using System.Collections.Generic;
using LitJson;

public class TestWWW : MonoBehaviour {

	void Start () {
		// IEnumeratorインターフェースを継承したメソッドは、StartCoroutineでコールする
		StartCoroutine(Get("http://www.google.co.jp"));
		StartCoroutine(Post("http://www.google.co.jp"));  // 今回は失敗します
	}
	
	void Update () {
	
	}

	IEnumerator Get (string url) {
		// HEADERはHashtableで記述
		Hashtable header = new Hashtable ();
		header.Add ("Accept-Language", "ja");

		// 送信開始
		WWW www = new WWW (url, null, header);
		yield return www;

		// 成功
		if (www.error == null) {
			Debug.Log("Get Success");

			// 本来はサーバからのレスポンスとしてjsonを戻し、www.textを使用するが
			// 今回は便宜上、下記のjsonを使用する
			string txt = "{\"name\": \"okude\", \"level\": 99, \"friend_names\": [\"ichiro\", \"jiro\", \"saburo\"]}";
			// 自作したTestResponseクラスにレスポンスを格納する
			TestResponse response = JsonMapper.ToObject<TestResponse> (txt);
			Debug.Log("name: " + response.name);
			Debug.Log("level: " + response.level);
			Debug.Log("friend_names[0]: " + response.friend_names[0]);
			Debug.Log("friend_names[1]: " + response.friend_names[1]);
			Debug.Log("friend_names[2]: " + response.friend_names[2]);
		}
		// 失敗
		else{
			Debug.Log("Get Failure");			
		}
	}

	IEnumerator Post (string url) {
		// HEADERはHashtableで記述
		Hashtable header = new Hashtable ();
		// jsonでリクエストを送るのへッダ例
		header.Add ("Content-Type", "application/json; charset=UTF-8");

		// LitJsonを使いJSONデータを生成
		JsonData data = new JsonData();
		data["hogehoge"] = 1;
		// シリアライズする(LitJson.JsonData→JSONテキスト)
		string postJsonStr = data.ToJson();
		byte[] postBytes = Encoding.Default.GetBytes (postJsonStr);

		// 送信開始
		WWW www = new WWW (url, postBytes, header);
		yield return www;

		// 成功
		if (www.error == null) {
			Debug.Log("Post Success");
		}
		// 失敗
		else{
			Debug.Log("Post Failure");			
		}
	}
	
}

// レスポンスのJSONを格納するクラス
class TestResponse {
	public string name;
	public int level;
	public List<string> friend_names;
}

追記

Uniwebを使うとさらにタイムアウトなどの機能があるのでさらに便利になりました。

TestWWW.cs
using UnityEngine;
using System.Collections;
using System.Text;
using LitJson;

public class TestWWW : MonoBehaviour {

	void Start () {
		StartCoroutine(Post());
	}

	IEnumerator Post () {
		JsonData data = new JsonData();

		data["name"] = "o-kuhiiro";
		data["age"] = 30;
		// bodyを作成
		byte[] postBytes = Encoding.Default.GetBytes (data.ToJson());

		string url = "http://google.com/";
		//string url = "サイズが大きいファイルなどをいれるとタイムアウト";

		HTTP.Request r = new HTTP.Request ("POST", url, postBytes);
		//HTTP.Request r = new HTTP.Request("GET", url);

		// Headerを作成
		r.headers.Add ("Content-Type", "application/json; charset=UTF-8");
		r.headers.Add ("User-Agent", "iphone6Plus");

		// タイムアウト秒数を設定
		r.timeout = 3;

		yield return r.Send();

		// なにかエラー発生
		if (r.exception != null) {
			Debug.Log ("post request error: " + r.exception.ToString ());

			// タイムアウト発生
			if (r.exception is System.TimeoutException) {
				Debug.Log ("Request timed out.");
			// それ以外のエラー
			} else {
				Debug.Log ("Exception occured in request.");
			}
		} else if (r.response.status != 200) { 
			Debug.Log ("post request code:" + r.response.status);
		// 成功
		} else {
			Debug.Log ("post Success!!");
			Debug.Log ("returned data:" + r.response.Text);
		}

		// 通信終了
		Debug.Log ("WWW Done. " + url);
	}
}
84
83
1

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
84
83

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?