Skip to content

Instantly share code, notes, and snippets.

@xoxwgys56
Last active October 25, 2021 02:12
Show Gist options
  • Save xoxwgys56/158d1398d993e7246e21264e72597f2e to your computer and use it in GitHub Desktop.
Save xoxwgys56/158d1398d993e7246e21264e72597f2e to your computer and use it in GitHub Desktop.
UnityPostRequestSample
using System.Collections;
using UnityEngine;
using UnityEngine.Networking;
using Newtonsoft.Json;
/// <summary>
/// This sample code work properly on Unity2020.3 <br/>
/// </summary>
public class UnityPostRequestSample : MonoBehaviour {
private const string URL = "http://localhost";
public void ParamRequest()
{
var form = new WWWForm();
form.AddField("param-key", "param-value");
var request = UnityWebRequest.Post(URL, form);
request.SetRequestHeader("Content-Type", "application/json");
Log("Start POST request with parameter.")
StartCoroutine(Request());
}
public void JsonBodyRequest()
{
var json = JsonConvert.SerializeObject(new {
key = "value",
NestedJson = {
key = "value"
}
})
var request = new UnityWebRequest(URL, "POST");
var jsonToSend = new System.Text.UTF8Encoding().GetBytes(jsonBody);
request.uploadHandler = new UploadHandlerRaw(jsonToSend);
request.downloadHandler = new DownloadHandlerBuffer();
request.SetRequestHeader("Content-Type", "application/json");
Log("Start POST request with json body.")
StartCoroutine(Request());
}
private IEnumerator Request()
{
// send request, and wait till get response.
yield return request.SendWebRequest();
if (request.result == UnityWebRequest.Result.ConnectionError ||
request.result == UnityWebRequest.Result.ProtocolError)
{
Log($"Failed get response with error code '{request.error}'.");
}
else
{
Log($"Succeed response with '{request.responseCode}'.");
// NOTE if you have any expectable object, replace `T` to `ExcpectableClass`
//
// var response = JsonConvert.DeserializeObject<T>(request.downloadHandler.text);
// NOTE if you wanna use callback method
//
// Callback()
//
// or you can inject variable using parameter
}
}
private void Callback()
{
Log("Not implemented.")
}
/// <summary>
/// If you use custom logger, change implementation.
/// </summary>
/// <param name="message">message</param>
/// <returns></returns>
private void Log(object message) => Debug.Log(message);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment