Asynchronous HTTP request
-------------------------------------------
We can create asyn http web request
public static async Task<string> RequestAsync(string UrlReq, string requestxml)
{
WebRequest webRequest;
string Response = string.Empty;
try
{
var postData = requestxml;
var url = new Uri(UrlReq, UriKind.Absolute);
webRequest = WebRequest.Create(url);
webRequest.Method = "POST";
webRequest.ContentType = "text/xml";
webRequest.Timeout = 20000;
webRequest.Headers.Add("Accept-Encoding: gzip");
using (Stream postStream = await webRequest.GetRequestStreamAsync())
{
byte[] byteArray = Encoding.UTF8.GetBytes(postData);
await postStream.WriteAsync(byteArray, 0, byteArray.Length);
await postStream.FlushAsync();
}
try
{
var response = (HttpWebResponse)await webRequest.GetResponseAsync();
Stream streamResponse = response.GetResponseStream();
if (response.Headers["Content-Encoding"].ToLower().Contains("gzip"))
{
streamResponse = new GZipStream(streamResponse, CompressionMode.Decompress);
}
using (StreamReader reader = new StreamReader(streamResponse))
{
Response = await reader.ReadToEndAsync();
}
response.Dispose();
streamResponse.Dispose();
if (Response == "")
{
return Response;
}
else
{
return Response;
}
}
catch (WebException Wex)
{
string WebError = new StreamReader(wex.Response.GetResponseStream()).ReadToEnd().ToString();
return WebError ;
}
}
catch (Exception ex)
{
return Response;
}
}
0 comments:
Post a Comment