Skip to content

Instantly share code, notes, and snippets.

@dbacinski
Last active July 6, 2021 13:33
Show Gist options
  • Star 13 You must be signed in to star a gist
  • Fork 2 You must be signed in to fork a gist
  • Save dbacinski/5bd2793e33b0377ecfbcd980d6841f1e to your computer and use it in GitHub Desktop.
Save dbacinski/5bd2793e33b0377ecfbcd980d6841f1e to your computer and use it in GitHub Desktop.
using System.Threading.Tasks;
using Newtonsoft.Json;
using Refit;
using System.Net.Http;
using System;
namespace wms_xamarin
{
public class LoginApi
{
private static readonly string baseUrl = "https://example.com";
public async Task<LoginResponse> loginWithCredentials(string login, string password)
{
var httpClient = new HttpClient(new HttpLoggingHandler(/*new NativeMessageHandler()*/)){ BaseAddress = new Uri(baseUrl)};
var api = RestService.For<ILoginApi>(httpClient);
var request = new LoginRequest {Email = login, Password = password};
return await api.LoginWithOAuth(request);
}
}
public class LoginRequest
{
[AliasAs("email")]
public string Email { get; set; }
[AliasAs("password")]
public string Password { get; set; }
[AliasAs("clientId")]
public string ClientId => "cientId";
[AliasAs("grant_type")]
public string GrantType => "password";
}
public class LoginResponse
{
[AliasAs("access_token")]
public string AccessToken { get; set; }
[AliasAs("token_type")]
public string TokenType { get; set; }
[AliasAs("expires_in")]
public string ExpiresIn { get; set; }
[AliasAs("refresh_token")]
public string RefreshToken { get; set; }
[AliasAs("created_at")]
public string CreatedAt { get; set; }
}
[Headers("User-Agent: Xamarin")]
public interface ILoginApi
{
[Post("/oauth/token")]
Task<LoginResponse> LoginWithOAuth([Body(BodySerializationMethod.UrlEncoded)] LoginRequest request);
}
}
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Threading;
using System.Threading.Tasks;
namespace wms_xamarin
{
public class HttpLoggingHandler : DelegatingHandler
{
public HttpLoggingHandler(HttpMessageHandler innerHandler = null) : base(
innerHandler ?? new HttpClientHandler())
{
}
protected override async Task<HttpResponseMessage> SendAsync(HttpRequestMessage request,
CancellationToken cancellationToken)
{
await Task.Delay(1, cancellationToken).ConfigureAwait(false);
var start = DateTime.Now;
var req = request;
var msg = $"[{req.RequestUri.PathAndQuery} - Request]";
Debug.WriteLine($"{msg}========Request Start==========");
Debug.WriteLine($"{msg} {req.Method} {req.RequestUri.PathAndQuery} {req.RequestUri.Scheme}/{req.Version}");
Debug.WriteLine($"{msg} Host: {req.RequestUri.Scheme}://{req.RequestUri.Host}");
foreach (var header in req.Headers)
{
Debug.WriteLine($"{msg} {header.Key}: {string.Join(", ", header.Value)}");
}
if (req.Content != null)
{
foreach (var header in req.Content.Headers)
{
Debug.WriteLine($"{msg} {header.Key}: {string.Join(", ", header.Value)}");
}
Debug.WriteLine($"{msg} Content:");
if (req.Content is StringContent || IsTextBasedContentType(req.Headers) || IsTextBasedContentType(req.Content.Headers))
{
var result = await req.Content.ReadAsStringAsync();
Debug.WriteLine($"{msg} {string.Join("", result.Cast<char>().Take(256))}...");
}
}
var response = await base.SendAsync(request, cancellationToken).ConfigureAwait(false);
Debug.WriteLine($"{msg}==========Request End==========");
msg = $"[{req.RequestUri.PathAndQuery} - Response]";
Debug.WriteLine($"{msg}=========Response Start=========");
var resp = response;
Debug.WriteLine($"{msg} {req.RequestUri.Scheme.ToUpper()}/{resp.Version} {(int) resp.StatusCode} {resp.ReasonPhrase}");
foreach (var header in resp.Headers)
{
Debug.WriteLine($"{msg} {header.Key}: {string.Join(", ", header.Value)}");
}
if (resp.Content != null)
{
foreach (var header in resp.Content.Headers)
{
Debug.WriteLine($"{msg} {header.Key}: {string.Join(", ", header.Value)}");
}
Debug.WriteLine($"{msg} Content:");
if (resp.Content is StringContent || IsTextBasedContentType(resp.Headers) || IsTextBasedContentType(resp.Content.Headers))
{
var result = await resp.Content.ReadAsStringAsync();
Debug.WriteLine($"{msg} {string.Join("", result.Cast<char>().Take(256))}...");
}
}
Debug.WriteLine($"{msg} Duration: {DateTime.Now - start}");
Debug.WriteLine($"{msg}==========Response End==========");
return response;
}
readonly string[] types = {"html", "text", "xml", "json", "txt", "x-www-form-urlencoded"};
private bool IsTextBasedContentType(HttpHeaders headers)
{
IEnumerable<string> values;
if (!headers.TryGetValues("Content-Type", out values))
return false;
var header = string.Join(" ", values).ToLowerInvariant();
return types.Any(t => header.Contains(t));
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment