C# 5.0 TAP 模式下的HTTP Get和Post

时间:2021-05-21 07:05:27

标题有点瘆人,换了工作之后很少写代码了,之前由于签了保密协议,不敢把代码拿出来分享给大家,只能摘抄网上的, 今斗胆拿出来晒晒,跪求指点,直接上代码吧

     public class HTTPHelper : IDisposable
{
const string urlbaseEndPoint = @"http://hk-uat-sharedapi.com"; HttpItem httpItem; public HTTPHelper(HttpItem item)
{
httpItem = item;
} public void HttpHelperMethod()
{
Uri target = new Uri(urlbaseEndPoint + httpItem.RelatedAddress);
WebRequest webquest = HttpWebRequest.Create(target);
//HttpWebRequest webquest = new HttpWebRequest();
//webquest.Accept = "application/hal+json";
webquest.Method = httpItem.RequestMethod.ToString();
webquest.ContentType = httpItem.Content_Type;
webquest.Headers["Authorization"] = httpItem.Authorization;
// webquest.Headers["Accept"] = "application/hal+json";
if (httpItem.RequestMethod == "Post")
{
using (StreamWriter requestWriter1 = new StreamWriter(webquest.GetRequestStream()))
{ requestWriter1.Write(httpItem.HttpMsgBodyContent);
requestWriter1.Flush();
}
}
webquest.GetResponseAsync().ContinueWith(GetResponseTask =>
{
Console.WriteLine( httpItem.RelatedAddress+": "+GetResponseTask.Status);
try
{
HttpWebResponse t = GetResponseTask.Result as HttpWebResponse;
Console.WriteLine(t.StatusCode.ToString()); if (!GetResponseTask.IsFaulted)
{ StreamReader reader = new StreamReader(GetResponseTask.Result.GetResponseStream());
if (reader != null)
{
string responseresult = reader.ReadToEnd();
//TODO: analysis the result and put the href into the list
// Console.WriteLine(responseresult);
} }
}
catch (Exception ex)
{
Console.WriteLine(httpItem.RelatedAddress + ex.InnerException.Message);
}
}); // Console.WriteLine(string.Format("scheduled the task {0},pending for getting the result", httpItem.RelatedAddress)); } public void Dispose()
{ }
}