コガネブログ

平日更新を目標に Unity や C#、Visual Studio、ReSharper などのゲーム開発アレコレを書いていきます

【Unity】UnityWebRequest で JSON を POST 通信するサンプル

概要

using System;
using System.Text;
using UnityEngine;
using UnityEngine.Networking;

public class Example : MonoBehaviour
{
    [Serializable]
    private sealed class Data
    {
        public int    id   = 25;
        public string name = "ピカチュウ";
    }

    private void Awake()
    {
        var url      = "https://httpbin.org/post";
        var data     = new Data();
        var json     = JsonUtility.ToJson( data );
        var postData = Encoding.UTF8.GetBytes( json );

        using var request = new UnityWebRequest( url, UnityWebRequest.kHttpVerbPOST )
        {
            uploadHandler   = new UploadHandlerRaw( postData ),
            downloadHandler = new DownloadHandlerBuffer()
        };

        request.SetRequestHeader( "Content-Type", "application/json" );

        var operation = request.SendWebRequest();

        operation.completed += _ =>
        {
            Debug.Log( operation.isDone );
            Debug.Log( operation.webRequest.downloadHandler.text );
            Debug.Log( operation.webRequest.isHttpError );
            Debug.Log( operation.webRequest.isNetworkError );
        };
    }
}

関連記事