Advertisement
Guest User

Untitled

a guest
Oct 9th, 2017
100
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.78 KB | None | 0 0
  1. An error occured while sending the request (Inner Exception: The underlying conection was closed: An unexpected error occured on a send)
  2.  
  3. public async Task<string> GetToken(string username, string password)
  4. {
  5. using (var client = new HttpClient())
  6. {
  7. InitializeHttpClient(client);
  8.  
  9. HttpContent requestContent = new StringContent("grant_type=password&username=" + username + "&password=" + password, Encoding.UTF8, "application/x-www-form-urlencoded");
  10.  
  11. var response = await client.PostAsync("token", requestContent);
  12.  
  13. if (response == null || response.StatusCode == HttpStatusCode.BadRequest)
  14. return null;
  15.  
  16. if (response.StatusCode == HttpStatusCode.NotFound
  17. || response.StatusCode == HttpStatusCode.RequestTimeout
  18. || response.StatusCode == HttpStatusCode.BadGateway
  19. || response.StatusCode == HttpStatusCode.ServiceUnavailable)
  20. {
  21. throw new Exception("No Connection to Web Service");
  22. }
  23.  
  24. var bearerData = response.Content.ReadAsStringAsync().Result;
  25.  
  26. return JObject.Parse(bearerData)["access_token"].ToString();
  27. }
  28. }
  29.  
  30.  
  31. private void InitializeHttpClient(HttpClient client)
  32. {
  33. client.BaseAddress = new Uri(_webServiceAddress);
  34. client.DefaultRequestHeaders.Accept.Clear();
  35. client.DefaultRequestHeaders.Add("User-Agent", "Test Client");
  36. }
  37.  
  38. private void InitializeHttpClient(HttpClient client, string token)
  39. {
  40. InitializeHttpClient(client);
  41. client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
  42. client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("bearer", token);
  43.  
  44. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement