diff --git a/Runtime/APIClient.cs b/Runtime/APIClient.cs index 292fbda..c120f37 100644 --- a/Runtime/APIClient.cs +++ b/Runtime/APIClient.cs @@ -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; @@ -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 @@ -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 GetAsync(string path, Action onError = default) + public async UniTask GetAsync(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(reader); - - if (response.Headers.TryGetValues("X-Authorization", out var keys)) + case HttpStatusCode.OK: { - BearerToken = keys.FirstOrDefault(); - } + IsConnected = true; + var res = serializer.Deserialize(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) @@ -177,40 +173,42 @@ public async UniTask GetAsync(string path, Action onError = return default; } - public async UniTask SendAsync(string relativePath, REQUEST_TYPE data) + public async UniTask SendAsync(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(reader); - - if (httpResponse.Headers.TryGetValues("X-Authorization", out var keys)) + case HttpStatusCode.OK: { - BearerToken = keys.FirstOrDefault(); - } + IsConnected = true; + var responseObject = serializer.Deserialize(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; @@ -219,5 +217,17 @@ public async UniTask SendAsync(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 } } diff --git a/package.json b/package.json index 9cba97f..66818f9 100644 --- a/package.json +++ b/package.json @@ -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": [