Skip to content

Instantly share code, notes, and snippets.

@camarin24
Created February 9, 2018 15:39
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save camarin24/abc3670cd2f29ed3add32fb2aec1f104 to your computer and use it in GitHub Desktop.
Save camarin24/abc3670cd2f29ed3add32fb2aec1f104 to your computer and use it in GitHub Desktop.
C# Web Client
public class WebClient
{
public string AccessToken { get; set; }
public string BaseUrl { get; set; }
/// <summary>
/// Cliente para hacer peticiones REST Json
/// </summary>
/// <param name="baseUrl">Url base para realizar las peticiones. No debe tener / al final, este se pone automaticamente.</param>
public WebClient(string baseUrl, string accessToken)
{
this.AccessToken = accessToken;
this.BaseUrl = baseUrl;
}
public ResponseContract<T> Post<T>(string url, object data, bool useOAuthAuthorization)
{
HttpClientHandler handler = new HttpClientHandler();
HttpClient client = new HttpClient();
if (useOAuthAuthorization)
{
AuthorizeClient(client);
}
var stringContent = JsonConvert.SerializeObject(data);
var buffer = System.Text.Encoding.UTF8.GetBytes(stringContent);
var byteContent = new ByteArrayContent(buffer);
byteContent.Headers.ContentType = new MediaTypeHeaderValue("application/json");
HttpResponseMessage response = client.PostAsync(string.Format("{0}/{1}", BaseUrl, url), byteContent).Result;
if (response.IsSuccessStatusCode)
{
ResponseContract<T> responseDTO = new ResponseContract<T>();
try
{
responseDTO.Data = JsonConvert.DeserializeObject<T>(response.Content.ReadAsStringAsync().Result);
}
catch (Exception ex)
{
}
return responseDTO;
}
return new ResponseContract<T>();
}
private HttpClient AuthorizeClient(HttpClient client)
{
client.DefaultRequestHeaders.Authorization = new System.Net.Http.Headers.AuthenticationHeaderValue("Bearer", AccessToken);
return client;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment