程序師世界是廣大編程愛好者互助、分享、學習的平台,程序師世界有你更精彩!
首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫知識
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
 程式師世界 >> 編程語言 >> .NET網頁編程 >> C# >> C#入門知識 >> C#通過WebClient/HttpWebRequest實現http的POST/GET方法,

C#通過WebClient/HttpWebRequest實現http的POST/GET方法,

編輯:C#入門知識

C#通過WebClient/HttpWebRequest實現http的POST/GET方法,


/// <summary>
///body是要傳遞的參數,格式"roleId=1&uid=2"
///post的cotentType填寫"application/x-www-form-urlencoded"
///soap填寫:"text/xml; charset=utf-8"
/// </summary>
public static string PostHttp(string url, string body, string contentType)
    {
        HttpWebRequest httpWebRequest = (HttpWebRequest)WebRequest.Create(url);

        httpWebRequest.ContentType = contentType;
        httpWebRequest.Method = "POST";
        httpWebRequest.Timeout = 20000;

        byte[] btBodys = Encoding.UTF8.GetBytes(body);
        httpWebRequest.ContentLength = btBodys.Length;
        httpWebRequest.GetRequestStream().Write(btBodys, 0, btBodys.Length);

        HttpWebResponse httpWebResponse = (HttpWebResponse)httpWebRequest.GetResponse();
        StreamReader streamReader = new StreamReader(httpWebResponse.GetResponseStream());
        string responseContent = streamReader.ReadToEnd();

        httpWebResponse.Close();
        streamReader.Close();
        httpWebRequest.Abort();
        httpWebResponse.Close();

        return responseContent;
    }
 1 /// <summary>
 2         /// 通過WebClient類Post數據到遠程地址,需要Basic認證;
 3         /// 調用端自己處理異常
 4         /// </summary>
 5         /// <param name="uri"></param>
 6         /// <param name="paramStr">name=張三&age=20</param>
 7         /// <param name="encoding">請先確認目標網頁的編碼方式</param>
 8         /// <param name="username"></param>
 9         /// <param name="password"></param>
10         /// <returns></returns>
11         public static string Request_WebClient(string uri, string paramStr, Encoding encoding, string username, string password)
12         {
13             if (encoding == null)
14                 encoding = Encoding.UTF8;
15 
16             string result = string.Empty;
17 
18             WebClient wc = new WebClient();
19 
20             // 采取POST方式必須加的Header
21             wc.Headers.Add("Content-Type", "application/x-www-form-urlencoded");
22 
23             byte[] postData = encoding.GetBytes(paramStr);
24 
25             if (!string.IsNullOrEmpty(username) && !string.IsNullOrEmpty(password))
26             {
27                 wc.Credentials = GetCredentialCache(uri, username, password);
28                 wc.Headers.Add("Authorization", GetAuthorization(username, password));
29             }
30 
31             byte[] responseData = wc.UploadData(uri, "POST", postData); // 得到返回字符流
32             return encoding.GetString(responseData);// 解碼                  
33         }
1 public static string GetHttp(string url, HttpContext httpContext) 2 { 3 string queryString = "?"; 4 5 foreach (string key in httpContext.Request.QueryString.AllKeys) 6 { 7 queryString += key + "=" + httpContext.Request.QueryString[key] + "&"; 8 } 9 10 queryString = queryString.Substring(0, queryString.Length - 1); 11 12 HttpWebRequest httpWebRequest = (HttpWebRequest)WebRequest.Create(url + queryString); 13 14 httpWebRequest.ContentType = "application/json"; 15 httpWebRequest.Method = "GET"; 16 httpWebRequest.Timeout = 20000; 17 18 //byte[] btBodys = Encoding.UTF8.GetBytes(body); 19 //httpWebRequest.ContentLength = btBodys.Length; 20 //httpWebRequest.GetRequestStream().Write(btBodys, 0, btBodys.Length); 21 22 HttpWebResponse httpWebResponse = (HttpWebResponse)httpWebRequest.GetResponse(); 23 StreamReader streamReader = new StreamReader(httpWebResponse.GetResponseStream()); 24 string responseContent = streamReader.ReadToEnd(); 25 26 httpWebResponse.Close(); 27 streamReader.Close(); 28 29 return responseContent; 30 } HttpWebRequest(GET)
 1 /// <summary>
 2         /// 通過 WebRequest/WebResponse 類訪問遠程地址並返回結果,需要Basic認證;
 3         /// 調用端自己處理異常
 4         /// </summary>
 5         /// <param name="uri"></param>
 6         /// <param name="timeout">訪問超時時間,單位毫秒;如果不設置超時時間,傳入0</param>
 7         /// <param name="encoding">如果不知道具體的編碼,傳入null</param>
 8         /// <param name="username"></param>
 9         /// <param name="password"></param>
10         /// <returns></returns>
11         public static string Request_WebRequest(string uri, int timeout, Encoding encoding, string username, string password)
12         {
13             string result = string.Empty;
14 
15             WebRequest request = WebRequest.Create(new Uri(uri));
16 
17             if (!string.IsNullOrEmpty(username) && !string.IsNullOrEmpty(password))
18             {
19                 request.Credentials = GetCredentialCache(uri, username, password);
20                 request.Headers.Add("Authorization", GetAuthorization(username, password));
21             }
22 
23             if (timeout > 0)
24                 request.Timeout = timeout;
25 
26             WebResponse response = request.GetResponse();
27             Stream stream = response.GetResponseStream();
28             StreamReader sr = encoding == null ? new StreamReader(stream) : new StreamReader(stream, encoding);
29 
30             result = sr.ReadToEnd();
31 
32             sr.Close();
33             stream.Close();
34 
35             return result;
36         }
37 
38         #region # 生成 Http Basic 訪問憑證 #
39 
40         private static CredentialCache GetCredentialCache(string uri, string username, string password)
41         {
42             string authorization = string.Format("{0}:{1}", username, password);
43 
44             CredentialCache credCache = new CredentialCache();
45             credCache.Add(new Uri(uri), "Basic", new NetworkCredential(username, password));
46 
47             return credCache;
48         }
49 
50         private static string GetAuthorization(string username, string password)
51         {
52             string authorization = string.Format("{0}:{1}", username, password);
53 
54             return "Basic " + Convert.ToBase64String(new ASCIIEncoding().GetBytes(authorization));
55         }
56 
57         #endregion

 

  1. 上一頁:
  2. 下一頁:
Copyright © 程式師世界 All Rights Reserved