40
36

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.

UnityWebRequestでjsonをpostしたい.

Posted at

ちょいハマったのでメモ。

SamplePost.cs
using System.Collections;
using System.Text;
using UnityEngine;
using UnityEngine.Networking;

public class SamplePost : MonoBehaviour
{
    void Start()
    {
        StartCoroutine(Post("http://localhost:4567", "{'nickname':'hoge'}"));
    }

    IEnumerator Post(string url, string bodyJsonString)
    {
        var request = new UnityWebRequest(url, "POST");
        byte[] bodyRaw = Encoding.UTF8.GetBytes(bodyJsonString);
        request.uploadHandler = (UploadHandler) new UploadHandlerRaw(bodyRaw);
        request.downloadHandler = (DownloadHandler) new DownloadHandlerBuffer();
        request.SetRequestHeader("Content-Type", "application/json");

        yield return request.Send();

        Debug.Log("Status Code: " + request.responseCode);
    }
}

UnityWebRequest.Post() のショートカットはフォームデータのポストしか対応してないので自分でnewする必要がある。
SetRequestHeaderContent-Typeを設定すればjsonのpostになる。

40
36
0

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
40
36

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?