Skip to content

Instantly share code, notes, and snippets.

@r2d2rigo
Last active March 14, 2023 07:44
Show Gist options
  • Save r2d2rigo/6121674 to your computer and use it in GitHub Desktop.
Save r2d2rigo/6121674 to your computer and use it in GitHub Desktop.

Revisions

  1. r2d2rigo renamed this gist Jul 31, 2013. 1 changed file with 0 additions and 0 deletions.
    File renamed without changes.
  2. r2d2rigo created this gist Jul 31, 2013.
    78 changes: 78 additions & 0 deletions gistfile1.cs
    Original 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;
    });
    }
    }