Skip to content

Commit

Permalink
feature/add-custom-headers (#2)
Browse files Browse the repository at this point in the history
* refactor APIClient.cs

* add SetDefaultHeader & RemoveDefaultHeader method to APIClient.cs

* set up new version
  • Loading branch information
gbviktor authored Apr 5, 2023
1 parent 1d0b21f commit 3046d9a
Show file tree
Hide file tree
Showing 2 changed files with 72 additions and 62 deletions.
132 changes: 71 additions & 61 deletions Runtime/APIClient.cs
Original file line number Diff line number Diff line change
Expand Up @@ -3,10 +3,11 @@
using System.Net;
using System.Linq;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Text;

using Cysharp.Threading.Tasks;

using JetBrains.Annotations;
using Newtonsoft.Json;

using UnityEngine;
Expand All @@ -16,33 +17,19 @@ namespace MontanaGames.JsonAPIClient

public class APIClient
{
public bool IsConnected
{
get;
set;
}
public bool IsConnected { get; private set; }

#region Header for Editor
#if UNITY_EDITOR
const string EditorHeader = "x-unity-editor";

string EditorHeaderValue = "";
private const string EditorHeader = "x-unity-editor";

public APIClient SetEditorAPIKey(string key)
{
EditorHeaderValue = key;
ApplyEditorHeader();
SetDefaultHeader(EditorHeader, key);
return this;
}

#endif
private void ApplyEditorHeader()
{
#if UNITY_EDITOR
client.DefaultRequestHeaders.Remove(EditorHeader);
client.DefaultRequestHeaders.Add(EditorHeader, EditorHeaderValue);
#endif
}
#endregion

#region Bearer Token Header
Expand Down Expand Up @@ -127,45 +114,54 @@ public APIClient(string baseUrl, JsonSerializerSettings SerializerSettings = def

client = new HttpClient(handler);
client.Timeout = TimeSpan.FromSeconds(19);

ApplyEditorHeader();
}


public APIClient SetDefaultHeader(string headerName, string headerValue)
{
client.DefaultRequestHeaders.Remove(headerName);
client.DefaultRequestHeaders.Add(headerName, headerValue);
return this;
}
public APIClient RemoveDefaultHeader(string headerName)
{
client.DefaultRequestHeaders.Remove(headerName);
return this;
}
#endregion

public async UniTask<RESPONSE> GetAsync<RESPONSE>(string path, Action onError = default)
public async UniTask<ResponseType> GetAsync<ResponseType>(string path, Action onError = default)
{
try
{
var requestUrl = $"{baseUrl}/{path}";
var response = await client.GetAsync(requestUrl);

using var getSteam = await response.Content.ReadAsStreamAsync();
await using var getSteam = await response.Content.ReadAsStreamAsync();

using StreamReader sr = new StreamReader(getSteam);
using var sr = new StreamReader(getSteam);
using JsonReader reader = new JsonTextReader(sr);

var statusCode = response.StatusCode;
if (statusCode == HttpStatusCode.OK)
switch (statusCode)
{
IsConnected = true;
RESPONSE res = serializer.Deserialize<RESPONSE>(reader);

if (response.Headers.TryGetValues("X-Authorization", out var keys))
case HttpStatusCode.OK:
{
BearerToken = keys.FirstOrDefault();
}
IsConnected = true;
var res = serializer.Deserialize<ResponseType>(reader);

return res;
}
if (statusCode == HttpStatusCode.Unauthorized)
{
onUnathorized?.Invoke();
} else
{
onError?.Invoke();
onRequestNotOk?.Invoke((int)statusCode);
Debug.Log($"{response.StatusCode}:{response.Content}");
var headers = response.Headers;
ApplyBearerTokenFromResponseHeader(headers);

return res;
}
case HttpStatusCode.Unauthorized:
onUnathorized?.Invoke();
break;
default:
onError?.Invoke();
onRequestNotOk?.Invoke((int)statusCode);
Debug.Log($"{response.StatusCode}:{response.Content}");
break;
}

} catch (Exception er)
Expand All @@ -177,40 +173,42 @@ public async UniTask<RESPONSE> GetAsync<RESPONSE>(string path, Action onError =
return default;
}

public async UniTask<RESPONSE_TYPE> SendAsync<REQUEST_TYPE, RESPONSE_TYPE>(string relativePath, REQUEST_TYPE data)
public async UniTask<ResponseType> SendAsync<RequestType, ResponseType>(string relativePath, RequestType data, Action onError = default)
{
try
{
var requestUrl = $"{baseUrl}/{relativePath}";

var httpResponse = await client.PostAsync(requestUrl,
var response = await client.PostAsync(requestUrl,
new StringContent(ToJsonString(data), Encoding.UTF8));

var s = await httpResponse.Content.ReadAsStreamAsync();
var responseStream = await response.Content.ReadAsStreamAsync();

using StreamReader sr = new StreamReader(s);
using var sr = new StreamReader(responseStream);
using JsonReader reader = new JsonTextReader(sr);

var statusCode = httpResponse.StatusCode;
if (statusCode == HttpStatusCode.OK)
var statusCode = response.StatusCode;
switch (statusCode)
{
IsConnected = true;
RESPONSE_TYPE res = serializer.Deserialize<RESPONSE_TYPE>(reader);

if (httpResponse.Headers.TryGetValues("X-Authorization", out var keys))
case HttpStatusCode.OK:
{
BearerToken = keys.FirstOrDefault();
}
IsConnected = true;
var responseObject = serializer.Deserialize<ResponseType>(reader);

return res;
} else if (statusCode == HttpStatusCode.Unauthorized)
{
onUnathorized?.Invoke();
} else
{
Debug.Log($"{statusCode}:{httpResponse.Content}");
var headers = response.Headers;
ApplyBearerTokenFromResponseHeader(headers);

return responseObject;
}
case HttpStatusCode.Unauthorized:
onUnathorized?.Invoke();
break;
default:
onError?.Invoke();
onRequestNotOk?.Invoke((int)statusCode);
Debug.Log($"{statusCode}:{response.Content}");
break;
}

} catch (Exception er)
{
IsConnected = false;
Expand All @@ -219,5 +217,17 @@ public async UniTask<RESPONSE_TYPE> SendAsync<REQUEST_TYPE, RESPONSE_TYPE>(strin

return default;
}

#region Utilities

private void ApplyBearerTokenFromResponseHeader([NotNull] HttpResponseHeaders headers)
{
if (headers == null) throw new ArgumentNullException(nameof(headers));
if (headers.TryGetValues("X-Authorization", out var keys))
{
BearerToken = keys.FirstOrDefault();
}
}
#endregion
}
}
2 changes: 1 addition & 1 deletion package.json
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@
"name": "Victor Bisterfeld",
"url": "https://gbviktor.de/json-api-client-for-unity"
},
"version": "1.0.0",
"version": "1.1.0",
"unity": "2021.1",
"description": "help you to boost up your first API service communication with JSON as payload and Bearer authorization Scheme",
"keywords": [
Expand Down

0 comments on commit 3046d9a

Please sign in to comment.