コガネブログ

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

【Unity】UnityWebRequest で JSON を POST 通信できなかった時

概要

using System;
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 );

        using var request = UnityWebRequest.Post( url, json );

        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 );
        };
    }
}

UnityWebRequest.Post を使用したらサーバーに JSON を送信できなかった

request.downloadHandler = (DownloadHandler) new DownloadHandlerBuffer();
if (string.IsNullOrEmpty(postData))
    return;
byte[] bytes = Encoding.UTF8.GetBytes(WWWTranscoder.DataEncode(postData, Encoding.UTF8));
request.uploadHandler = (UploadHandler) new UploadHandlerRaw(bytes);
request.uploadHandler.contentType = "application/x-www-form-urlencoded";

UnityWebRequest.Post の処理を見てみたら
サーバーに送信する JSON をWWWTranscoder.DataEncode でエンコードしていた

{"id":25,"name":"ピカチュウ"}

そのため、サーバーに上記のような JSON を送ろうとしたら

%7b%22id%22%3a25%2c%22name%22%3a%22%e3%83%94%e3%82%ab%e3%83%81%e3%83%a5%e3%82%a6%22%7d

このようにエンコードされてしまっており、JSON を送信できていなかった

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 );
        };
    }
}

UnityWebRequest.Post を使わない書き方にしたら正常に送信できた