Skip to content

Instantly share code, notes, and snippets.

@TheAlphamerc
Last active October 30, 2018 08:45
Show Gist options
  • Save TheAlphamerc/d5d04adb7e44c2247a907bc433b2e82a to your computer and use it in GitHub Desktop.
Save TheAlphamerc/d5d04adb7e44c2247a907bc433b2e82a to your computer and use it in GitHub Desktop.
Consume Rest Client API Service Xamarin Form
using Newtonsoft.Json;
using System;
using System.Net;
using System.Net.Http;
using System.Text;
using System.Threading.Tasks;
namespace ApiServices
{
public class WebApiRestClient
{
private readonly JsonSerializerSettings _jsonSettings;
Uri baseUri = new Uri("{Your API Uri base address here}");
public WebApiRestClient()
{
_jsonSettings = new JsonSerializerSettings
{
ReferenceLoopHandling = ReferenceLoopHandling.Ignore,
MissingMemberHandling = MissingMemberHandling.Ignore,
DateTimeZoneHandling = DateTimeZoneHandling.Utc,
DateFormatHandling = DateFormatHandling.IsoDateFormat,
NullValueHandling = NullValueHandling.Ignore,
DefaultValueHandling = DefaultValueHandling.Include
};
}
private static HttpClient _instance;
private static HttpClient HttpClientInstance => _instance ?? (_instance = new HttpClient());
public async Task<TResponse> GetAsync<TResponse>(string uri)
{
try
{
HttpResponseMessage response = await HttpClientInstance.GetAsync((uri)).ConfigureAwait(false); ;
return await HandleResponse<TResponse>(response);
}
catch(Exception)
{
throw;
}
}
public async Task<TResponse> PostAsync<TRequest, TResponse>(string action, TRequest request)
{
Uri uri = new Uri(baseUri, action);
var json = JsonConvert.SerializeObject(request, _jsonSettings);
var content = new StringContent(json.ToString(), Encoding.UTF8, "application/json");
try
{
var response = await HttpClientInstance.PostAsync(uri, content).ConfigureAwait(false);
return await HandleResponse<TResponse>(response);
}
catch(Exception)
{
throw;
}
}
private async Task<TResponse> HandleResponse<TResponse>(HttpResponseMessage response)
{
if (!response.IsSuccessStatusCode)
{
var content = await response.Content.ReadAsStringAsync();
if (response.StatusCode == HttpStatusCode.Forbidden || response.StatusCode == HttpStatusCode.Unauthorized)
{
throw new Exception(content);
}
else if (response.StatusCode == HttpStatusCode.RequestTimeout)
{
throw new WebException("Request Time out");
}
else if (response.StatusCode == HttpStatusCode.InternalServerError)
{
throw new WebException("Internel server Error");
}
else if (response.StatusCode == HttpStatusCode.GatewayTimeout)
{
throw new WebException("Gateway Timeout");
}
else if (response.StatusCode == HttpStatusCode.BadRequest)
{
throw new WebException("Bad Requst");
}
throw new HttpRequestException(content);
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment