Last active
March 14, 2023 07:44
-
-
Save r2d2rigo/6121674 to your computer and use it in GitHub Desktop.
Revisions
-
r2d2rigo renamed this gist
Jul 31, 2013 . 1 changed file with 0 additions and 0 deletions.There are no files selected for viewing
File renamed without changes. -
r2d2rigo created this gist
Jul 31, 2013 .There are no files selected for viewing
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 charactersOriginal file line number Diff line number Diff line change @@ -0,0 +1,78 @@ using System; using System.Collections.Generic; using System.IO; using System.Net; using System.Text; using System.Threading.Tasks; public class AsyncHttpWebRequest { private HttpWebRequest webRequest; public async Task<string> DoRequest(Uri uri, string method, string contentType, Dictionary<string, string> postParameters) { this.webRequest = (HttpWebRequest)HttpWebRequest.CreateHttp(uri); this.webRequest.Method = method; this.webRequest.ContentType = contentType; if (method == "POST") { await this.SendPostData(postParameters); } return await this.GetWebContent(); } private async Task SendPostData(Dictionary<string, string> parameters) { await Task<Stream>.Factory.FromAsync(this.webRequest.BeginGetRequestStream, this.webRequest.EndGetRequestStream, this.webRequest) .ContinueWith(streamResult => { using (Stream postStream = streamResult.Result) { string postData = string.Empty; int count = 0; foreach (KeyValuePair<string, string> kvp in parameters) { postData += kvp.Key + "=" + kvp.Value; if (++count < parameters.Count) { postData += "&"; } } byte[] byteArray = Encoding.UTF8.GetBytes(postData); postStream.Write(byteArray, 0, byteArray.Length); } }); } private async Task<string> GetWebContent() { return await Task<WebResponse>.Factory.FromAsync(this.webRequest.BeginGetResponse, this.webRequest.EndGetResponse, this.webRequest) .ContinueWith<string>(webResponseResult => { string responseString = string.Empty; try { using (HttpWebResponse response = (HttpWebResponse)webResponseResult.Result) { using (StreamReader streamRead = new StreamReader(response.GetResponseStream())) { responseString = streamRead.ReadToEnd(); } } } catch (Exception e) { responseString = null; } return responseString; }); } }