Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- An error occured while sending the request (Inner Exception: The underlying conection was closed: An unexpected error occured on a send)
- public async Task<string> GetToken(string username, string password)
- {
- using (var client = new HttpClient())
- {
- InitializeHttpClient(client);
- HttpContent requestContent = new StringContent("grant_type=password&username=" + username + "&password=" + password, Encoding.UTF8, "application/x-www-form-urlencoded");
- var response = await client.PostAsync("token", requestContent);
- if (response == null || response.StatusCode == HttpStatusCode.BadRequest)
- return null;
- if (response.StatusCode == HttpStatusCode.NotFound
- || response.StatusCode == HttpStatusCode.RequestTimeout
- || response.StatusCode == HttpStatusCode.BadGateway
- || response.StatusCode == HttpStatusCode.ServiceUnavailable)
- {
- throw new Exception("No Connection to Web Service");
- }
- var bearerData = response.Content.ReadAsStringAsync().Result;
- return JObject.Parse(bearerData)["access_token"].ToString();
- }
- }
- private void InitializeHttpClient(HttpClient client)
- {
- client.BaseAddress = new Uri(_webServiceAddress);
- client.DefaultRequestHeaders.Accept.Clear();
- client.DefaultRequestHeaders.Add("User-Agent", "Test Client");
- }
- private void InitializeHttpClient(HttpClient client, string token)
- {
- InitializeHttpClient(client);
- client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
- client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("bearer", token);
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement