Advertisement
RokasC

Untitled

Jan 8th, 2019
83
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.76 KB | None | 0 0
  1. // public async Task<string> GetJson(string path)
  2. // {
  3. // var result = string.Empty;
  4. // var response = await client.GetAsync(path);
  5. //
  6. // if (response.IsSuccessStatusCode)
  7. // {
  8. // result = await response.Content.ReadAsStringAsync();
  9. // }
  10. // else
  11. // {
  12. // result = null;
  13. // }
  14. // return result;
  15. // }
  16.  
  17. public async Task<string> GetJson(string path)
  18. {
  19. var result = String.Empty;
  20. try
  21. {
  22. HttpWebRequest myHttpWebRequest = (HttpWebRequest)WebRequest.Create(path);
  23. HttpWebResponse myHttpWebResponse = (HttpWebResponse)myHttpWebRequest.GetResponse();
  24. if (myHttpWebResponse.StatusCode == HttpStatusCode.OK)
  25. {
  26. Task<WebResponse> task = Task.Factory.FromAsync(
  27. myHttpWebRequest.BeginGetResponse,
  28. asyncResult => myHttpWebRequest.EndGetResponse(asyncResult),
  29. (object) null);
  30. var resultStream = task.Result.GetResponseStream();
  31. using (Stream stream = resultStream)
  32. {
  33. StreamReader sr = new StreamReader(stream, Encoding.UTF8);
  34. result = sr.ReadToEnd();
  35. }
  36. myHttpWebResponse.Close();
  37. }
  38.  
  39. }
  40. catch (WebException e)
  41. {
  42. result = null;
  43. }
  44. return result;
  45. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement