码迷,mamicode.com
首页 > Web开发 > 详细

通过WebClient/HttpWebRequest实现http的post/get方法

时间:2015-06-24 14:20:57      阅读:163      评论:0      收藏:0      [点我收藏+]

标签:


 1 ///<summary>/// 通过WebClient类Post数据到远程地址,需要Basic认证;
 2 /// 调用端自己处理异常
 3 ///</summary>///<param name="uri"></param>///<param name="paramStr">name=张三&age=20</param>///<param name="encoding">请先确认目标网页的编码方式</param>///<param name="username"></param>///<param name="password"></param>///<returns></returns>publicstaticstring Request_WebClient(string uri, string paramStr, Encoding encoding, string username, string password)
 4         {
 5 if (encoding == null)
 6                  encoding = Encoding.UTF8;
 7 string result = string.Empty;
 8 
 9              WebClient wc = new WebClient();
10 // 采取POST方式必须加的Header
11              wc.Headers.Add("Content-Type", "application/x-www-form-urlencoded");
12 byte[] postData = encoding.GetBytes(paramStr);
13 if (!string.IsNullOrEmpty(username) && !string.IsNullOrEmpty(password))
14             {
15                  wc.Credentials = GetCredentialCache(uri, username, password);
16                  wc.Headers.Add("Authorization", GetAuthorization(username, password));
17             }
18 byte[] responseData = wc.UploadData(uri, "POST", postData); // 得到返回字符流return encoding.GetString(responseData);// 解码                  
19          }
20   
21       //get方法
22 publicstaticstring GetHttp(string url, HttpContext httpContext)
23     {
24 string queryString = "?";
25 foreach (string key in httpContext.Request.QueryString.AllKeys)
26         {
27              queryString += key + "=" + httpContext.Request.QueryString[key] + "&";
28         }
29  
30         queryString = queryString.Substring(0, queryString.Length - 1);
31  
32          HttpWebRequest httpWebRequest = (HttpWebRequest)WebRequest.Create(url + queryString);
33  
34          httpWebRequest.ContentType = "application/json";
35          httpWebRequest.Method = "GET";
36          httpWebRequest.Timeout = 20000;
37 //byte[] btBodys = Encoding.UTF8.GetBytes(body);
38 //httpWebRequest.ContentLength = btBodys.Length;
39 //httpWebRequest.GetRequestStream().Write(btBodys, 0, btBodys.Length);
40  
41          HttpWebResponse httpWebResponse = (HttpWebResponse)httpWebRequest.GetResponse();
42          StreamReader streamReader = new StreamReader(httpWebResponse.GetResponseStream());
43 string responseContent = streamReader.ReadToEnd();
44         httpWebResponse.Close();
45         streamReader.Close();
46 return responseContent;
47      }
48 
49 ///<summary>/// 通过 WebRequest/WebResponse 类访问远程地址并返回结果,需要Basic认证;
50 /// 调用端自己处理异常
51 ///</summary>///<param name="uri"></param>///<param name="timeout">访问超时时间,单位毫秒;如果不设置超时时间,传入0</param>///<param name="encoding">如果不知道具体的编码,传入null</param>///<param name="username"></param>///<param name="password"></param>///<returns></returns>publicstaticstring Request_WebRequest(string uri, int timeout, Encoding encoding, string username, string password)
52         {
53 string result = string.Empty;
54  
55              WebRequest request = WebRequest.Create(new Uri(uri));
56 if (!string.IsNullOrEmpty(username) && !string.IsNullOrEmpty(password))
57             {
58                  request.Credentials = GetCredentialCache(uri, username, password);
59                  request.Headers.Add("Authorization", GetAuthorization(username, password));
60             }
61 if (timeout > 0)
62                  request.Timeout = timeout;
63  
64              WebResponse response = request.GetResponse();
65              Stream stream = response.GetResponseStream();
66              StreamReader sr = encoding == null ? new StreamReader(stream) : new StreamReader(stream, encoding);
67  
68              result = sr.ReadToEnd();
69             sr.Close();
70             stream.Close();
71 return result;
72         }
73 #region # 生成 Http Basic 访问凭证 #
74  
75          privatestatic CredentialCache GetCredentialCache(string uri, string username, string password)
76         {
77 string authorization = string.Format("{0}:{1}", username, password);
78  
79              CredentialCache credCache = new CredentialCache();
80              credCache.Add(new Uri(uri), "Basic", new NetworkCredential(username, password));
81 return credCache;
82         }
83 privatestaticstring GetAuthorization(string username, string password)
84         {
85 string authorization = string.Format("{0}:{1}", username, password);
86 return"Basic " + Convert.ToBase64String(new ASCIIEncoding().GetBytes(authorization));
87         }
88 #endregion

 

 1 //body是要传递的参数,格式"roleId=1&uid=2"
 2 //post的cotentType填写:
 3 //"application/x-www-form-urlencoded"
 4 //soap填写:"text/xml; charset=utf-8"
 5 public static string PostHttp(string url, string body, string contentType)
 6     {
 7          HttpWebRequest httpWebRequest = (HttpWebRequest)WebRequest.Create(url);
 8  
 9          httpWebRequest.ContentType = contentType;
10          httpWebRequest.Method = "POST";
11          httpWebRequest.Timeout = 20000;
12 byte[] btBodys = Encoding.UTF8.GetBytes(body);
13          httpWebRequest.ContentLength = btBodys.Length;
14          httpWebRequest.GetRequestStream().Write(btBodys, 0, btBodys.Length);
15  
16          HttpWebResponse httpWebResponse = (HttpWebResponse)httpWebRequest.GetResponse();
17          StreamReader streamReader = new StreamReader(httpWebResponse.GetResponseStream());
18 string responseContent = streamReader.ReadToEnd();
19         httpWebResponse.Close();
20         streamReader.Close();
21         httpWebRequest.Abort();
22         httpWebResponse.Close();
23 return responseContent;
24      }

 

通过WebClient/HttpWebRequest实现http的post/get方法

标签:

原文地址:http://www.cnblogs.com/chuanxiaoxi/p/4597363.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!