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.
An elegant way of asynchronously requesting web sites on Windows Phone.
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;
});
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment