Last active
March 19, 2017 07:02
-
-
Save JoachimL/b9d025a11aa27692d05376645827d57c to your computer and use it in GitHub Desktop.
Set up of kolonial client
This file contains hidden or 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 static async Task<HttpClient> CreateKolonialHttpClientAsync(){ | |
var httpClient = new HttpClient(); | |
// The kolonial API requires a client token and a user agent (supplied by kolonial) to work | |
httpClient.DefaultRequestHeaders.Add("X-Client-Token", ConfigurationManager.AppSettings["KolonialToken"]); | |
httpClient.DefaultRequestHeaders.Add("User-Agent", ConfigurationManager.AppSettings["KolonialUserAgent"]); | |
// Modifying the cart requires a valid, active session | |
string sessionId = await GetSessionIdAsync(httpClient); | |
// Ensure the session cookie is sent as part of the calls to the API. | |
httpClient.DefaultRequestHeaders.Add("Cookie", $"sessionid={sessionId}"); | |
return httpClient; | |
} | |
public static async Task<string> GetSessionIdAsync(HttpClient httpClient) | |
{ | |
// The session cookie ID is retrieved by passing an object like { username: "something", password: "something-secure" } | |
// to the user/login endpoint | |
var result = await httpClient.PostAsync("https://kolonial.no/api/v1/user/login/", | |
new StringContent( | |
JsonConvert.SerializeObject( | |
new { username = "an-email-address", password = "a-password" }), | |
Encoding.UTF8, "application/json")); | |
result.EnsureSuccessStatusCode(); | |
var json = await result.Content.ReadAsStringAsync(); | |
var response = JsonConvert.DeserializeObject<LogInResponse>(json); | |
return response.sessionid; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment