Last active
August 29, 2015 14:25
-
-
Save trinvh2/362564021aa30e9b6f85 to your computer and use it in GitHub Desktop.
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
using System; | |
using System.Collections.Generic; | |
using System.Linq; | |
using System.Text; | |
using System.Threading.Tasks; | |
using System.Net; | |
using System.Net.Http; | |
using System.Net.Http.Headers; | |
using Newtonsoft.Json; | |
namespace iMovies.Api | |
{ | |
public class HttpProvider | |
{ | |
private static HttpClient client; | |
private static HttpResponseHeaders responseHeaders; | |
public static async Task<string> Post(string url, Dictionary<string, string> parameters) | |
{ | |
client = new HttpClient(); | |
BeforeRequest(); | |
FormUrlEncodedContent form = new FormUrlEncodedContent(parameters); | |
HttpResponseMessage resp = await client.PostAsync(url, form); | |
responseHeaders = resp.Headers; | |
string content = await resp.Content.ReadAsStringAsync(); | |
AfterRequest(content); | |
return content; | |
} | |
public static async Task<string> Get(string url) | |
{ | |
client = new HttpClient(); | |
BeforeRequest(); | |
HttpResponseMessage resp = await client.GetAsync(url); | |
responseHeaders = resp.Headers; | |
string content = await resp.Content.ReadAsStringAsync(); | |
AfterRequest(content); | |
return content; | |
} | |
private static void BeforeRequest() | |
{ | |
if (!string.IsNullOrEmpty(Config.Token)) | |
{ | |
client.DefaultRequestHeaders.Add("Authorization", "Bearer " + Config.Token); | |
} | |
} | |
private static void AfterRequest(string response) | |
{ | |
if (responseHeaders.Contains("Authorization")) | |
{ | |
string token = responseHeaders.GetValues("Authorization").FirstOrDefault(); | |
if (!string.IsNullOrEmpty(token)) | |
{ | |
Config.OldToken = Config.Token; | |
Config.Token = token.TrimStart("Bearer".ToCharArray()); | |
} | |
} | |
JsonError error = JsonConvert.DeserializeObject<JsonError>(response); | |
if (error.Error) { | |
if(error.Message.Contains("token") || error.Error.Contains("token")) { | |
throw new RequiredAuthException(); | |
} else { | |
throw new Exception(error.Message); | |
} | |
} | |
} | |
} | |
public class JsonError | |
{ | |
public string Error { get; set; } | |
public string Message { get; set; } | |
public JsonError(bool error, string message) | |
{ | |
this.Error = error; | |
this.Message = message; | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment