Skip to content

Instantly share code, notes, and snippets.

@JasonMore
Created June 3, 2014 20:31
Show Gist options
  • Save JasonMore/2da1ba0e9b30ae4ab48b to your computer and use it in GitHub Desktop.
Save JasonMore/2da1ba0e9b30ae4ab48b to your computer and use it in GitHub Desktop.
HttpWebRequest sync/async
public async Task<string> GetResponseAsStringAsync(HttpWebRequest webRequest, string post = null)
{
if (post != null)
{
webRequest.Method = "POST";
using (Stream postStream = await webRequest.GetRequestStreamAsync())
{
byte[] postBytes = Encoding.ASCII.GetBytes(post);
await postStream.WriteAsync(postBytes, 0, postBytes.Length);
await postStream.FlushAsync();
}
}
try
{
Task<string> Response;
using (var response = (HttpWebResponse)await webRequest.GetResponseAsync())
using (Stream streamResponse = response.GetResponseStream())
using (StreamReader streamReader = new StreamReader(streamResponse))
{
Response = streamReader.ReadToEndAsync();
}
// Ignore Warning: I don't want to await for this call, its for logging
Response.ContinueWith(async x =>
{
_logger.Info(new HttpRequestLog
{
Request = webRequest,
Url = webRequest.RequestUri.ToString(),
Method = webRequest.Method,
PostBody = post,
Response = await x
});
});
return await Response;
}
catch (Exception ee)
{
_logger.Error(new HttpErrorLog { Request = webRequest, Url = webRequest.RequestUri.ToString(), ExceptionMessage = ee.ToString(), PostBody = post });
return null;
}
}
public string GetResponseAsString(HttpWebRequest request, string post = null)
{
if (post != null)
{
request.Method = "POST";
byte[] postBytes = Encoding.ASCII.GetBytes(post);
request.ContentLength = postBytes.Length;
Stream requestStream = request.GetRequestStream();
requestStream.Write(postBytes, 0, postBytes.Length);
requestStream.Close();
}
try
{
using (HttpWebResponse httpGetResponse = (HttpWebResponse)request.GetResponse())
using (Stream strm = httpGetResponse.GetResponseStream())
using (StreamReader sr = new StreamReader(strm))
{
string sText = sr.ReadToEnd();
_logger.Info(new HttpRequestLog
{
Request = request,
Url = request.RequestUri.ToString(),
Method = request.Method,
PostBody = post,
Response = sText
});
return sText;
}
}
catch (Exception ee)
{
_logger.Error(new HttpErrorLog { Request = request, Url = request.RequestUri.ToString(), ExceptionMessage = ee.ToString(), PostBody = post });
return null;
}
}
@lyf-is-coding
Copy link

ty!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment