using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using System.Collections;
using System.Collections.Generic;
using System.IO;
using UnityEngine;
using UnityEngine.Networking;
public class NEW_API_TEST_POST : MonoBehaviour
{
// 입력에 필요한 변수들
string url = "URL";
string apiKey = "API KEY";
string player_session_id = "JSON Respons Body";
string bet_id = "JSON Respons Body";
void Start()
{
StartCoroutine(UnityWebRequestPost());
}
// 요청 시 JSON 포멧을 유지하기위한 데이터라고 보면됩니다.
// 실제로 json코드를 C#으로 변환하면 아래와 같은 코드가 나옵니다.
// 보통 string[]보단 List로 나올 것임.
public class postData
{
public string[] players_session_id;
public string bet_id;
}
// UnityWebRequest POST 방식
IEnumerator UnityWebRequestPost()
{
// postData 클래스의 객체를 만들고 Json 입력 데이터를 넣어줍니다.
postData postData = new postData();
postData.players_session_id = new string[1];
postData.players_session_id[0] = player_session_id;
postData.bet_id = bet_id;
// PostData를 Json포멧으로 직렬화합니다.
var param1 = JsonConvert.SerializeObject(postData);
using (UnityWebRequest www = UnityWebRequest.Post(url, param1))
{
byte[] jsonToSend = new System.Text.UTF8Encoding().GetBytes(param1);
www.uploadHandler = new UploadHandlerRaw(jsonToSend);
www.SetRequestHeader("api-key", apiKey);
www.SetRequestHeader("Content-Type", "application/json");
yield return www.SendWebRequest();
if (www.result == UnityWebRequest.Result.ConnectionError || www.result == UnityWebRequest.Result.ProtocolError)
{
Debug.Log(www.error);
yield break;
}
Debug.Log(www.downloadHandler.text);
// 자원 반납
www.Dispose();
}
}
}
댓글 영역