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

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

 1     public class HTTPHelper : IDisposable

 2     {

 3         const string urlbaseEndPoint = @"http://hk-uat-sharedapi.com";

 4 

 5         HttpItem httpItem;

 6 

 7         public HTTPHelper(HttpItem item)

 8         {

 9             httpItem = item;

10         }

11 

12         public void HttpHelperMethod()

13         {

14             Uri target = new Uri(urlbaseEndPoint + httpItem.RelatedAddress);

15             WebRequest webquest = HttpWebRequest.Create(target);

16             //HttpWebRequest webquest = new HttpWebRequest();

17             //webquest.Accept = "application/hal+json";

18             webquest.Method = httpItem.RequestMethod.ToString();

19             webquest.ContentType = httpItem.Content_Type;

20             webquest.Headers["Authorization"] = httpItem.Authorization;

21             // webquest.Headers["Accept"] = "application/hal+json";

22             if (httpItem.RequestMethod == "Post")

23             {

24                 using (StreamWriter requestWriter1 = new StreamWriter(webquest.GetRequestStream()))

25                 {

26 

27                     requestWriter1.Write(httpItem.HttpMsgBodyContent);

28                     requestWriter1.Flush();

29                 }

30             }

31             webquest.GetResponseAsync().ContinueWith(GetResponseTask =>

32             {

33                 Console.WriteLine( httpItem.RelatedAddress+": "+GetResponseTask.Status);

34                 try

35                 {

36                     HttpWebResponse t = GetResponseTask.Result as HttpWebResponse;

37                     Console.WriteLine(t.StatusCode.ToString());

38 

39                     if (!GetResponseTask.IsFaulted)

40                     {

41 

42                         StreamReader reader = new StreamReader(GetResponseTask.Result.GetResponseStream());

43                         if (reader != null)

44                         {

45                             string responseresult = reader.ReadToEnd();

46                             //TODO: analysis the result and put the href into the list 

47                            // Console.WriteLine(responseresult);

48                         }

49 

50                     }

51                 }

52                 catch (Exception ex)

53                 {

54                     Console.WriteLine(httpItem.RelatedAddress + ex.InnerException.Message);

55                 }

56             });

57 

58            // Console.WriteLine(string.Format("scheduled the task {0},pending for getting the result", httpItem.RelatedAddress));

59 

60 

61         }

62 

63         public void Dispose()

64         {

65            

66         }

67 }

你可能感兴趣的:(http)