Created
February 9, 2018 15:39
-
-
Save camarin24/abc3670cd2f29ed3add32fb2aec1f104 to your computer and use it in GitHub Desktop.
C# Web Client
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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