Created
July 24, 2011 01:30
-
-
Save prabirshrestha/1102085 to your computer and use it in GitHub Desktop.
Async/Await FluentHttp.Core Sample
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
| private async static Task<object> HttpAsync() | |
| { | |
| Stream input = new MemoryStream(Encoding.UTF8.GetBytes("message=hello")); | |
| var httpHelper = new HttpHelper("https://api.example.com"); | |
| var httpWebRequest = httpHelper.HttpWebRequest; | |
| httpWebRequest.Method = "POST"; | |
| if (input != null) | |
| { | |
| try | |
| { | |
| httpWebRequest.ContentLength = input.Length; | |
| using (var requestStream = await httpHelper.OpenWriteTaskAsync()) | |
| { | |
| int read; | |
| byte[] buffer = new byte[1024 * 4]; // 4 kb | |
| while ((read = input.Read(buffer, 0, buffer.Length)) != 0) | |
| { | |
| requestStream.Write(buffer, 0, read); | |
| } | |
| } | |
| } | |
| catch (WebExceptionWrapper ex) | |
| { | |
| if (ex.GetResponse() == null) | |
| throw; | |
| } | |
| finally | |
| { | |
| input.Dispose(); | |
| } | |
| } | |
| Stream responseStream = null; | |
| WebExceptionWrapper webException = null; | |
| try | |
| { | |
| responseStream = await httpHelper.OpenReadTaskAsync(); | |
| } | |
| catch (WebExceptionWrapper ex) | |
| { | |
| if (ex.GetResponse() == null) | |
| throw; | |
| webException = ex; | |
| } | |
| try | |
| { | |
| if (webException != null) | |
| responseStream = await httpHelper.OpenReadTaskAsync(); | |
| using (var reader = new StreamReader(responseStream)) | |
| { | |
| try | |
| { | |
| return JsonSerializer.Current.DeserializeObject(reader.ReadToEnd()); | |
| } | |
| catch (Exception ex) | |
| { | |
| throw webException == null ? ex : webException; | |
| } | |
| } | |
| } | |
| finally | |
| { | |
| if (responseStream != null) | |
| responseStream.Dispose(); | |
| } | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment