本Qiitaに関して
RESTでの接続方法に関してのまとめです。
関連Qiita
- DayDream開発機の設定
- UnityでのDayDreamデモアプリのBuild
- DayDream Readyのスマフォ
- DayDream開発機の作り方
- DayDream関連リンク
- Unity向けのWebSocketライブラリの組み込み
- UnityのJsonUtilityでJSON配列を処理する
REST
UnityのC#でRESTでたたきたい場合には、UnityWebRequestを利用する。
GET
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 ("success");
Debug.Log(request.downloadHandler.text);
} else {
Debug.Log ("failed");
}
}
}
POST
public IEnumerator Post (string url, string jsonStr) {
var request = new UnityWebRequest();
request.url = url;
byte[] body = Encoding.UTF8.GetBytes(jsonStr);
request.uploadHandler = new UploadHandlerRaw(body);
request.downloadHandler = new DownloadHandlerBuffer();
request.SetRequestHeader("Content-Type", "application/json; charset=UTF-8");
request.method = UnityWebRequest.kHttpVerbPOST;
yield return request.Send();
if(request.isError) {
Debug.Log(request.error);
}
else {
if (request.responseCode == 200) {
Debug.Log ("success");
Debug.Log(request.downloadHandler.text);
} else {
Debug.Log ("failed");
}
}
}
DELETE
public IEnumerator Delete (string url) {
var request = new UnityWebRequest();
request.url = url;
request.downloadHandler = new DownloadHandlerBuffer();
request.SetRequestHeader("Content-Type", "application/json; charset=UTF-8");
request.method = UnityWebRequest.kHttpVerbDELETE;
yield return request.Send();
if(request.isError) {
Debug.Log(request.error);
}
else {
if (request.responseCode == 200) {
Debug.Log ("success");
Debug.Log(request.downloadHandler.text);
} else {
Debug.Log ("failed");
}
}
}
PUT
public IEnumerator Put (string url, string jsonStr) {
var request = new UnityWebRequest();
request.url = url;
byte[] body = Encoding.UTF8.GetBytes(jsonStr);
request.uploadHandler = new UploadHandlerRaw(body);
request.downloadHandler = new DownloadHandlerBuffer();
request.SetRequestHeader("Content-Type", "application/json; charset=UTF-8");
request.method = UnityWebRequest.kHttpVerbPUT;
yield return request.Send();
if(request.isError) {
Debug.Log(request.error);
}
else {
if (request.responseCode == 200) {
Debug.Log ("success");
Debug.Log(request.downloadHandler.text);
} else {
Debug.Log ("failed");
}
}
}