Skip to content

Instantly share code, notes, and snippets.

@Finkes
Created October 21, 2016 00:23
Show Gist options
  • Save Finkes/a4299f9c485786bc12ac070f7a588807 to your computer and use it in GitHub Desktop.
Save Finkes/a4299f9c485786bc12ac070f7a588807 to your computer and use it in GitHub Desktop.
JSON REST Client for Unity 3D
using UnityEngine;
using System.Collections;
using UnityEngine.Networking;
public class JsonRestClient : MonoBehaviour {
private T fromJSON<T>(string json){
return JsonUtility.FromJson<T> (json);
}
private string toJSON<T>(T model){
return JsonUtility.ToJson(model);
}
public void Get<J> (string url, string successCallback, string errorCallback){
this.request<Object, J> (url, "GET", null, successCallback, errorCallback);
}
public void Post<T, J>(string url, T payload, string successCallback, string errorCallback){
this.request<T,J>(url, "POST", payload, successCallback, errorCallback);
}
public void Post<J>(string url, string successCallback, string errorCallback){
this.request<Object,J>(url, "POST", null, successCallback, errorCallback);
}
public void Put<T, J>(string url, T payload, string successCallback, string errorCallback){
this.request<T,J>(url, "PUT", payload, successCallback, errorCallback);
}
public void Put<J>(string url, string successCallback, string errorCallback){
this.request<Object,J>(url, "PUT", null, successCallback, errorCallback);
}
public void Delete<T, J>(string url, T payload, string successCallback, string errorCallback){
this.request<T,J>(url, "DELETE", payload, successCallback, errorCallback);
}
public void Delete<J>(string url, string successCallback, string errorCallback){
this.request<Object,J>(url, "DELETE", null, successCallback, errorCallback);
}
private void request<T, J>(string url, string method, T payload, string successCallback, string errorCallback){
this.StartCoroutine(this.handleAsyncRequest<T, J>(payload, method, url, successCallback, errorCallback));
}
private IEnumerator handleAsyncRequest<T, J>(T payload, string method, string url, string successCallback, string errorCallback){
UnityWebRequest webRequest = new UnityWebRequest (url, method);
byte[] payloadBytes;
if (payload != null) {
payloadBytes = System.Text.Encoding.UTF8.GetBytes (this.toJSON<T> (payload));
} else {
payloadBytes = System.Text.Encoding.UTF8.GetBytes ("{}");
}
UploadHandler upload = new UploadHandlerRaw (payloadBytes);
webRequest.uploadHandler = upload;
webRequest.downloadHandler = new DownloadHandlerBuffer ();
webRequest.SetRequestHeader ("Content-Type", "application/json");
yield return webRequest.Send();
if(webRequest.isError) {
gameObject.BroadcastMessage (errorCallback, webRequest.error);
}
else {
if (webRequest.responseCode < 200 || webRequest.responseCode >= 400) {
gameObject.BroadcastMessage (errorCallback, webRequest.downloadHandler.text);
} else {
var response = this.fromJSON<J>(webRequest.downloadHandler.text);
gameObject.BroadcastMessage (successCallback, response);
}
}
}
}
using UnityEngine;
using System.Collections;
[System.Serializable]
class RequestPayload {
public string stringData;
public int numberData;
public CustomData data;
}
[System.Serializable]
class ResponsePayload {
public CustomData data;
}
[System.Serializable]
class CustomData {
public string key;
}
public class WebRequestTest : MonoBehaviour {
public string url = "http://localhost:3000/api";
void Start () {
JsonRestClient restClient = GetComponent<JsonRestClient> ();
RequestPayload req = new RequestPayload ();
CustomData data = new CustomData ();
data.key = "value1";
req.data = data;
req.numberData = 123;
req.stringData = "stringData";
restClient.Get<ResponsePayload> (this.url+"?test=value", "onSuccess", "onError");
restClient.Post<RequestPayload, ResponsePayload> (this.url + "/test", null, "onSuccess", "onError");
restClient.Post<ResponsePayload> (this.url, "onSuccess", "onError");
restClient.Post<RequestPayload, ResponsePayload> (this.url, null, "onSuccess", "onError");
restClient.Put<RequestPayload, ResponsePayload> (this.url, null, "onSuccess", "onError");
restClient.Delete<RequestPayload, ResponsePayload> (this.url, null, "onSuccess", "onError");
}
void onSuccess(ResponsePayload response){
Debug.Log (response.data.key);
}
void onError(string error){
Debug.Log ("onError: " + error);
}
}
@jdnichollsc
Copy link

jdnichollsc commented Nov 1, 2017

@Finkes Hey my friend, what do you think about my REST Client for Unity? https://github.com/proyecto26/RestClient
I'm using a similar way to create the HTTP requests but supporting Promises! 👍

@maifeeulasad
Copy link

@jdnichollsc is surely cool approach, but sometimes, it makes you really embarrassed. Like : proyecto26/RestClient#179
Other than this issue, that repo is really cool. I've used it a lot.

But this piece of gist will never let you down.

@jdnichollsc
Copy link

@maifeeulasad any pull request is welcome! 👍

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment