C#中HttpWebRequest的用法詳解


原文地址:https://blog.csdn.net/zhruifei/article/details/78356347

1、HttpWebRequest和HttpWebResponse類是用於發送和接收HTTP數據的最好選擇。

2、命名空間:System.Net

3、HttpWebRequest對象不是利用new關鍵字創建的(通過構造函數)。 
而是利用Create()方法創建的。

4、你可能預計需要顯示地調用一個“Send”方法,實際上不需要。

5、調用 HttpWebRequest.GetResponse()方法返回的是一個HttpWebResponse對象

6、你可以把HTTP響應的數據流 (stream)綁定到一個StreamReader對象,然后就可以通過ReadToEnd()方法把整個HTTP響應作為一個字符串取回。也可以通過 StreamReader.ReadLine()方法逐行取回HTTP響應的內容。

下面是HttpWebRequest的一些屬性,這些屬性對於輕量級的自動化測試程序是非常重要的。

a) AllowAutoRedirect:獲取或設置一個值,該值指示請求是否應跟隨重定向響應。 
b)CookieContainer:獲取或設置與此請求關聯的cookie。 
c)Credentials:獲取或設置請求的身份驗證信息。 
d)KeepAlive:獲取或設置一個值,該值指示是否與 Internet 資源建立持久性連接。 
e)MaximumAutomaticRedirections:獲取或設置請求將跟隨的重定向的最大數目。 
f) Proxy:獲取或設置請求的代理信息。 
g)SendChunked:獲取或設置一個值,該值指示是否將數據分段發送到 Internet 資源。 
h)Timeout:獲取或設置請求的超時值。 
i) UserAgent:獲取或設置 User-agent HTTP 標頭的值

C# HttpWebRequest提交數據方式其實就是GET和POST兩種

C# HttpWebRequest的作用: 
HttpWebRequest對HTTP協議進行了完整的封裝,對HTTP協議中的 Header, Content, Cookie 都做了屬性和方法的支持,很容易就能編寫出一個模擬瀏覽器自動登錄的程序。

C# HttpWebRequest提交數據方式: 
程序使用HTTP協議和服務器交互主要是進行數據的提交,通常數據的提交是通過 GET 和 POST 兩種方式來完成,

C# HttpWebRequest提交數據方式

1. GET 方式。 
GET 方式通過在網絡地址附加參數來完成數據的提交,比如在地址 http://www.google.com/webhp?hl=zh-CN 中,前面部分 http://www.google.com/webhp 表示數據提交的網址,后面部分 hl=zh-CN 表示附加的參數,其中 hl 表示一個鍵(key), zh-CN 表示這個鍵對應的值(value)。程序代碼如下:

HttpWebRequest req =  
(HttpWebRequest)HttpWebRequest.Create("http://www.google.com/webhp?hl=zh-CN" ); 
req.Method = "GET"; 
using (WebResponse wr = req.GetResponse()) 
{ 
   //在這里對接收到的頁面內容進行處理 
}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7

2. POST 方式。

POST 方式通過在頁面內容中填寫參數的方法來完成數據的提交,參數的格式和 GET 方式一樣,是類似於 hl=zh-CN&newwindow=1 這樣的結構。程序代碼如下:

string param = "hl=zh-CN&newwindow=1";        //參數
byte[] bs = Encoding.ASCII.GetBytes(param);    //參數轉化為ascii碼
HttpWebRequest req = (HttpWebRequest) HttpWebRequest.Create("http://www.google.com/intl/zh-CN/" );  //創建request
req.Method = "POST";    //確定傳值的方式,此處為post方式傳值
req.ContentType = "application/x-www-form-urlencoded"; 
req.ContentLength = bs.Length; 
using (Stream reqStream = req.GetRequestStream()) 
{ 
   reqStream.Write(bs, 0, bs.Length); 
} 
using (WebResponse wr = req.GetResponse()) 
{ 
   //在這里對接收到的頁面內容進行處理 
} 
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14

3. 使用 GET 方式提交中文數據。

GET 方式通過在網絡地址中附加參數來完成數據提交,對於中文的編碼,常用的有 gb2312 和 utf8 兩種,用 gb2312 方式編碼訪問的程序代碼如下:

Encoding myEncoding = Encoding.GetEncoding("gb2312");     //確定用哪種中文編碼方式
string address = "http://www.baidu.com/s?"+ HttpUtility.UrlEncode("參數一", myEncoding) +  "=" + HttpUtility.UrlEncode("值一", myEncoding);       //拼接數據提交的網址和經過中文編碼后的中文參數
HttpWebRequest req =   (HttpWebRequest)HttpWebRequest.Create(address);  //創建request
req.Method = "GET";    //確定傳值方式,此處為get方式
using (WebResponse wr = req.GetResponse()) 
{ 
   //在這里對接收到的頁面內容進行處理 
} 
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8

在上面的程序代碼中,我們以 GET 方式訪問了網址 http://www.baidu.com/s ,傳遞了參數“參數一=值一”,由於無法告知對方提交數據的編碼類型,所以編碼方式要以對方的網站為標准。常見的網站中, www.baidu.com (百度)的編碼方式是 gb2312, www.google.com (谷歌)的編碼方式是 utf8。

4. 使用 POST 方式提交中文數據。

POST 方式通過在頁面內容中填寫參數的方法來完成數據的提交,由於提交的參數中可以說明使用的編碼方式,所以理論上能獲得更大的兼容性。用 gb2312 方式編碼訪問的程序代碼如下:

Encoding myEncoding = Encoding.GetEncoding("gb2312"); //確定中文編碼方式。此處用gb2312
string param =   HttpUtility.UrlEncode("參數一", myEncoding) +   "=" + HttpUtility.UrlEncode("值一", myEncoding) +   "&" +     HttpUtility.UrlEncode("參數二", myEncoding) +  "=" + HttpUtility.UrlEncode("值二", myEncoding); 
byte[] postBytes = Encoding.ASCII.GetBytes(param); //將參數轉化為assic碼
HttpWebRequest req = (HttpWebRequest)  HttpWebRequest.Create( "http://www.baidu.com/s" ); 
req.Method = "POST"; 
req.ContentType =   "application/x-www-form-urlencoded;charset=gb2312"; 
req.ContentLength = postBytes.Length; 
using (Stream reqStream = req.GetRequestStream()) 
{ 
   reqStream.Write(bs, 0, bs.Length); 
} 
using (WebResponse wr = req.GetResponse()) 
{ 
   //在這里對接收到的頁面內容進行處理 
}  
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15

從上面的代碼可以看出, POST 中文數據的時候,先使用 UrlEncode 方法將中文字符轉換為編碼后的 ASCII 碼,然后提交到服務器,提交的時候可以說明編碼的方式,用來使對方服務器能夠正確的解析。

以上列出了客戶端程序使用HTTP協議與服務器交互的情況,常用的是 GET 和 POST 方式。

現在流行的 WebService 也是通過 HTTP 協議來交互的,使用的是 POST 方法。與以上稍有所不同的是, WebService 提交的數據內容和接收到的數據內容都是使用了 XML 方式編碼。所以, HttpWebRequest 也可以使用在調用 WebService 的情況下。

C# HttpWebRequest提交數據方式的基本內容就向你介紹到這里,希望對你了解和學習C# HttpWebRequest提交數據方式有所幫助。

    #region 公共方法
    /// <summary>
    /// Get數據接口
    /// </summary>
    /// <param name="getUrl">接口地址</param>
    /// <returns></returns>
    private static string GetWebRequest(string getUrl)
    {
        string responseContent = "";

        HttpWebRequest request = (HttpWebRequest)WebRequest.Create(getUrl);
        request.ContentType = "application/json";
        request.Method = "GET";

        HttpWebResponse response = (HttpWebResponse)request.GetResponse();
        //在這里對接收到的頁面內容進行處理
        using (Stream resStream = response.GetResponseStream())
        {
            using (StreamReader reader = new StreamReader(resStream, Encoding.UTF8))
            {
                responseContent = reader.ReadToEnd().ToString();
            }
        }
        return responseContent;
    }
    /// <summary>
    /// Post數據接口
    /// </summary>
    /// <param name="postUrl">接口地址</param>
    /// <param name="paramData">提交json數據</param>
    /// <param name="dataEncode">編碼方式(Encoding.UTF8)</param>
    /// <returns></returns>
    private static string PostWebRequest(string postUrl, string paramData, Encoding dataEncode)
    {
        string responseContent = string.Empty;
        try
        {
            byte[] byteArray = dataEncode.GetBytes(paramData); //轉化
            HttpWebRequest webReq = (HttpWebRequest)WebRequest.Create(new Uri(postUrl));
            webReq.Method = "POST";
            webReq.ContentType = "application/x-www-form-urlencoded";
            webReq.ContentLength = byteArray.Length;
            using (Stream reqStream = webReq.GetRequestStream())
            {
                reqStream.Write(byteArray, 0, byteArray.Length);//寫入參數
                                                                //reqStream.Close();
            }
            using (HttpWebResponse response = (HttpWebResponse)webReq.GetResponse())
            {
                //在這里對接收到的頁面內容進行處理
                using (StreamReader sr = new StreamReader(response.GetResponseStream(), Encoding.Default))
                {
                    responseContent = sr.ReadToEnd().ToString();
                }
            }
        }
        catch (Exception ex)
        {
            return ex.Message;
        }
        return responseContent;
    }

    #endregion
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  • 32
  • 33
  • 34
  • 35
  • 36
  • 37
  • 38
  • 39
  • 40
  • 41
  • 42
  • 43
  • 44
  • 45
  • 46
  • 47
  • 48
  • 49
  • 50
  • 51
  • 52
  • 53
  • 54
  • 55
  • 56
  • 57
  • 58
  • 59
  • 60
  • 61
  • 62
  • 63
  • 64

OAuth頭部

//構造OAuth頭部 
StringBuilder oauthHeader = new StringBuilder();
oauthHeader.AppendFormat("OAuth realm=\"\", oauth_consumer_key={0}, ", apiKey);
oauthHeader.AppendFormat("oauth_nonce={0}, ", nonce);
oauthHeader.AppendFormat("oauth_timestamp={0}, ", timeStamp);
oauthHeader.AppendFormat("oauth_signature_method={0}, ", "HMAC-SHA1");
oauthHeader.AppendFormat("oauth_version={0}, ", "1.0");
oauthHeader.AppendFormat("oauth_signature={0}, ", sig);
oauthHeader.AppendFormat("oauth_token={0}", accessToken);

//構造請求 
StringBuilder requestBody = new StringBuilder("");
Encoding encoding = Encoding.GetEncoding("utf-8");
byte[] data = encoding.GetBytes(requestBody.ToString());

// Http Request的設置 
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(uri);
request.Headers.Set("Authorization", oauthHeader.ToString());
//request.Headers.Add("Authorization", authorization); 
request.ContentType = "application/atom+xml";
request.Method = "GET";
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21

C#通過WebClient/HttpWebRequest實現http的post/get方法

1.POST方法(httpWebRequest)

//body是要傳遞的參數,格式"roleId=1&uid=2"
//post的cotentType填寫:"application/x-www-form-urlencoded"
//soap填寫:"text/xml; charset=utf-8"
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;
}

復制代碼
    /// <summary>
    /// 用於外部接口調用封裝
    /// </summary>
    public static class ApiInterface
    {

        /// <summary>
        ///驗證密碼是否正確
        /// </summary>
        public static Api_ToConfig<object> checkPwd(int userId, string old)
        {
            var url = WebConfigManager.GetAppSettings("DataCenterUrl") + "/rest/user/checkPwd";
            var data = Json.ToObject<Api_ToConfig<object>>(CallWebRequest.Post(url + "?id=" + userId, "&oldPwd=" + old));
            //var data = Json.ToObject<Api_ToConfig<object>>(CallWebRequest.Post(url, "{\"id\":" + userId + ",oldPwd:\"" + old + "\",newPwd:\"" + pwd + "\"}"));
            return data;
        }

        /// <summary>
        ///
        /// </summary>
        public static Api_ToConfig<object> UpdatePassword(int userId, string pwd, string old)
        {
            var url = WebConfigManager.GetAppSettings("DataCenterUrl") + "/rest/user/updatePwd";
            var data = Json.ToObject<Api_ToConfig<object>>(CallWebRequest.Post(url + "?id=" + userId + "&oldPwd=" + old, "&newPwd=" + pwd));
            //var data = Json.ToObject<Api_ToConfig<object>>(CallWebRequest.Post(url, "{\"id\":" + userId + ",oldPwd:\"" + old + "\",newPwd:\"" + pwd + "\"}"));
            return data;
        }




        private static DateTime GetTime(string timeStamp)
        {
            DateTime dtStart = TimeZone.CurrentTimeZone.ToLocalTime(new DateTime(1970, 1, 1));
            long lTime = long.Parse(timeStamp + "0000");
            TimeSpan toNow = new TimeSpan(lTime); return dtStart.Add(toNow);
        }


        #region 公共方法

        /// <summary>
        /// 配置文件key
        /// </summary>
        /// <param name="key"></param>
        /// <param name="isOutKey"></param>
        /// <returns></returns>
        public static string GetConfig(string key, bool isOutKey = false)
        {
            //  CacheRedis.Cache.RemoveObject(RedisKey.ConfigList);
            var data = CacheRedis.Cache.Get<Api_BaseToConfig<Api_Config>>(RedisKey.ConfigList);

            //  var data = new Api_BaseToConfig<Api_Config>();
            if (data == null)
            {
                string dataCenterUrl = WebConfigManager.GetAppSettings("DataCenterUrl");
                string configurationInfoListByFilter = WebConfigManager.GetAppSettings("ConfigurationInfoListByFilter");

                string systemCoding = WebConfigManager.GetAppSettings("SystemCoding");
                string nodeIdentifier = WebConfigManager.GetAppSettings("NodeIdentifier");
                string para = "systemIdf=" + systemCoding + "&nodeIdf=" + nodeIdentifier + "";
                //string para = "{\"systemIdf\":\"" + systemCoding + "\",\"nodeIdf\":\"" + nodeIdentifier + "\"}";

                string result = CallWebRequest.Post(dataCenterUrl + "/rest" + configurationInfoListByFilter, para);
                data =
                    Json.ToObject<Api_BaseToConfig<Api_Config>>(result);
                CacheRedis.Cache.Set(RedisKey.ConfigList, data);
            }
            if (data.Status)
            {
                if (isOutKey && ConfigServer.IsOutside())
                {
                    key += "_outside";
                }
                key = key.ToLower();
                var firstOrDefault = data.Data.FirstOrDefault(e => e.Identifier.ToLower() == key);
                if (firstOrDefault != null)
                {
                    return firstOrDefault.Value;
                }
                else
                {
                    if (key.IndexOf("_outside") > -1)
                    {
                        firstOrDefault = data.Data.FirstOrDefault(e => e.Identifier == key.Substring(0, key.LastIndexOf("_outside")));
                        if (firstOrDefault != null)
                            return firstOrDefault.Value;
                    }
                }
            }
            return "";
        }

        public static string WebPostRequest(string url, string postData)
        {
            return CallWebRequest.Post(url, postData);
        }
        public static string WebGetRequest(string url)
        {
            return CallWebRequest.Get(url);
        }

        #endregion


        #region 參數轉換方法
        private static string ConvertClassIds(string classIds)
        {
            var list = classIds.Split(',');
            StringBuilder sb = new StringBuilder("{\"class_id_list\": [");
            foreach (var s in list)
            {
                sb.Append("{\"classId\": \"" + s + "\"},");
            }
            if (list.Any())
                sb.Remove(sb.Length - 1, 1);

            sb.Append("]}");

            return sb.ToString();
        }

        private static string ConvertLabIds(string labIds)
        {
            var list = labIds.Split(',');
            StringBuilder sb = new StringBuilder("{\"lab_id_list\": [");
            foreach (var s in list)
            {
                sb.Append("{\"labId\": \"" + s + "\"},");
            }
            if (list.Any())
                sb.Remove(sb.Length - 1, 1);

            sb.Append("]}");

            return sb.ToString();
        }

        private static string ConvertCardNos(string cardNos)
        {
            var list = cardNos.Split(',');
            StringBuilder sb = new StringBuilder("{\"student_cardNos_list\": [");
            foreach (var s in list)
            {
                sb.Append("{\"stuCardNo\": \"" + s + "\"},");
            }
            if (list.Any())
                sb.Remove(sb.Length - 1, 1);

            sb.Append("]}");

            return sb.ToString();
        }
        #endregion



        /// <summary>
        /// 設置公文已讀
        /// </summary>
        /// <param name="beginTime"></param>
        /// <param name="endTime"></param>
        /// <param name="userId"></param>
        /// <param name="currentPage"></param>
        /// <param name="pageSize"></param>
        /// <returns></returns>
        public static Api_ToConfig<object> FlowService(string id)
        {
            var url = WebConfigManager.GetAppSettings("FlowService");
            var data = Json.ToObject<Api_ToConfig<object>>(CallWebRequest.Post(url + "?Copyid=" + id, ""));
            return data;
        }


        /// <summary>
        ///獲取OA工作流數據
        /// </summary>
        public static string getOAWorkFlowData(string userName, string userId)
        {
            var url = GetConfig("platform.application.oa.url") + WebConfigManager.GetAppSettings("OAWorkFlowData");
            var data = CallWebRequest.Post(url, "&account=" + userName + "&userId=" + userId);
            return data;

        }

        public static List<Api_Course> GetDreamClassCourse(string userId)
        {
            List<Api_Course> list = new List<Api_Course>();
            list = CacheRedis.Cache.Get<List<Api_Course>>(RedisKey.DreamCourse + userId);
            if (list != null && list.Count > 0)
                return list;

            var url = GetConfig("platform.system.dreamclass.url", true) + "rest/getTeacherCourseInfo";
            var result = Json.ToObject<ApiResult<Api_Course>>(CallWebRequest.Post(url, "&userId=" + userId));
            if (result.state)
                list = result.data;
            CacheRedis.Cache.Set(RedisKey.DreamCourse + userId, list, 30);//緩存30分鍾失效
            return list;
        }

        /// <summary>
        /// 用戶信息
        /// </summary>
        /// <param name="userId"></param>
        /// <returns></returns>
        public static Api_User GetUserInfoByUserName(string userName)
        {
            var model = new Api_User();
            var url = WebConfigManager.GetAppSettings("DataCenterUrl") + "/rest/user/getUserInfoByUserName";
            var result = Json.ToObject<ApiBase<Api_User>>(CallWebRequest.Post(url, "&userName=" + userName));
            if (result.status == true && result.data != null)
                model = result.data;
            return model;
        }

        public static Api_User GetUserInfoByUserId(string userId)
        {
            var model = new Api_User();
            var url = WebConfigManager.GetAppSettings("DataCenterUrl") + "/rest/user/getUserInfoByUserId";
            var result = Json.ToObject<ApiBase<Api_User>>(CallWebRequest.Get(url + "?userId=" + userId));
            if (result.status == true && result.data != null)
                model = result.data;
            return model;
        }

        public static Api_User GetUserByUserId(string userId)
        {
            var model = new Api_User();
            var url = WebConfigManager.GetAppSettings("DataCenterUrl") + "/rest/user/getUserByUserId";
            var result = Json.ToObject<ApiBase<Api_User>>(CallWebRequest.Get(url + "?userId=" + userId));
            if (result.status == true && result.data != null)
                model = result.data;
            return model;
        }


        public static ApiBase<string> UserExist(string userName)
        {
            ApiBase<string> result = new ApiBase<string>();
            var url = WebConfigManager.GetAppSettings("DataCenterUrl") + "/rest/user/checkUserExists";
            result = Json.ToObject<ApiBase<string>>(CallWebRequest.Post(url, "&userName=" + userName));
            return result;

        }
        public static ApiBase<string> CheckUserPwd(string userName, string pwd)
        {
            ApiBase<string> result = new ApiBase<string>();
            var url = WebConfigManager.GetAppSettings("DataCenterUrl") + "/rest/user/checkUserPsw";
            result = Json.ToObject<ApiBase<string>>(CallWebRequest.Post(url, "&userName=" + userName + "&psw=" + pwd));
            return result;

        }
        public static ApiBase<Api_AnswerQuestion> GetAnswerQuestion(string userName)
        {
            ApiBase<Api_AnswerQuestion> result = new ApiBase<Api_AnswerQuestion>();
            var url = WebConfigManager.GetAppSettings("DataCenterUrl") + "/rest/safety/getSafetyByUserName";
            result = Json.ToObject<ApiBase<Api_AnswerQuestion>>(CallWebRequest.Post(url, "&userName=" + userName));
            return result;
        }

        public static ApiBase<string> ResetUserPassword(string userName, string newPassWord)
        {
            ApiBase<string> result = new ApiBase<string>();
            var url = WebConfigManager.GetAppSettings("DataCenterUrl") + "/rest/user/resetUserPasswordByUserName";
            result = Json.ToObject<ApiBase<string>>(CallWebRequest.Post(url, "&userName=" + userName + "&newPassWord=" + newPassWord));
            return result;
        }
        public static ApiBase<string> ChangeUserSafeAnswer(string userId, string answer1, string answer2, string answer3, string safeId)
        {
            ApiBase<string> result = new ApiBase<string>();
            var url = WebConfigManager.GetAppSettings("DataCenterUrl") + "/rest/safety/batchUpdageSafety";
            result = Json.ToObject<ApiBase<string>>(CallWebRequest.Post(url, "&data=[{editor:\"" + userId + "\",safetyAnswerOne:\"" + answer1 + "\",safetyAnswerTwo:\"" + answer2 + "\",safetyAnswerThree:\"" + answer3 + "\",safetyId:" + safeId + "}]"));
            return result;
        }

        public static ApiBase<string> UpdateUserPhoto(string userId, string userPhoto)
        {
            ApiBase<string> result = new ApiBase<string>();
            var url = WebConfigManager.GetAppSettings("DataCenterUrl") + "/rest/user/updataUserInfo";
            result = Json.ToObject<ApiBase<string>>(CallWebRequest.Post(url, "&data=[{userId:\"" + userId + "\",userPhoto:\"" + userPhoto + "\"}]"));
            return result;
        }

        public static Api_DreamClassUserInfo GetDreamClassUser(string userId)
        {
            var model = new Api_DreamClassUserInfo();
            //model = CacheRedis.Cache.Get<Api_DreamClassUserInfo>(RedisKey.DreamCourseUser + userId);
            var url = GetConfig("platform.system.dreamclass.url", true) + "rest/getUserInfo";
            var result = Json.ToObject<ApiBase<Api_DreamClassUserInfo>>(CallWebRequest.Post(url, "&userId=" + userId));
            if (result.state == true && result.data != null)
            {
                model = result.data;
                //CacheRedis.Cache.Set(RedisKey.DreamCourseUser+userId,model);
            }

            return model;
        }

        public static List<Api_BitCourse> GetBitCourseList(string userName)
        {
            List<Api_BitCourse> list = new List<Api_BitCourse>();
            list = CacheRedis.Cache.Get<List<Api_BitCourse>>(RedisKey.BitCourse + userName);
            if (list != null && list.Count > 0)
                return list;
            try
            {
                var url = GetConfig("platform.system.szhjxpt.url", true) + "/Services/DtpServiceWJL.asmx/GetMyCourseByLoginName";
                var result = Json.ToObject<ApiConfig<Api_BitCourse>>(CallWebRequest.Post(url, "&loginName=" + userName));

                if (result.success)
                    list = result.datas;
                CacheRedis.Cache.Set(RedisKey.BitCourse + userName, list, 30);//緩存30分鍾失效
            }
            catch (Exception exception)
            {
                list = new List<Api_BitCourse>();
                Log.Error(exception.Message);
            }

            return list;
        }
    }
復制代碼

1、HttpWebRequest和HttpWebResponse類是用於發送和接收HTTP數據的最好選擇。

2、命名空間:System.Net

3、HttpWebRequest對象不是利用new關鍵字創建的(通過構造函數)。 
而是利用Create()方法創建的。

4、你可能預計需要顯示地調用一個“Send”方法,實際上不需要。

5、調用 HttpWebRequest.GetResponse()方法返回的是一個HttpWebResponse對象

6、你可以把HTTP響應的數據流 (stream)綁定到一個StreamReader對象,然后就可以通過ReadToEnd()方法把整個HTTP響應作為一個字符串取回。也可以通過 StreamReader.ReadLine()方法逐行取回HTTP響應的內容。

下面是HttpWebRequest的一些屬性,這些屬性對於輕量級的自動化測試程序是非常重要的。

a) AllowAutoRedirect:獲取或設置一個值,該值指示請求是否應跟隨重定向響應。 
b)CookieContainer:獲取或設置與此請求關聯的cookie。 
c)Credentials:獲取或設置請求的身份驗證信息。 
d)KeepAlive:獲取或設置一個值,該值指示是否與 Internet 資源建立持久性連接。 
e)MaximumAutomaticRedirections:獲取或設置請求將跟隨的重定向的最大數目。 
f) Proxy:獲取或設置請求的代理信息。 
g)SendChunked:獲取或設置一個值,該值指示是否將數據分段發送到 Internet 資源。 
h)Timeout:獲取或設置請求的超時值。 
i) UserAgent:獲取或設置 User-agent HTTP 標頭的值

C# HttpWebRequest提交數據方式其實就是GET和POST兩種

C# HttpWebRequest的作用: 
HttpWebRequest對HTTP協議進行了完整的封裝,對HTTP協議中的 Header, Content, Cookie 都做了屬性和方法的支持,很容易就能編寫出一個模擬瀏覽器自動登錄的程序。

C# HttpWebRequest提交數據方式: 
程序使用HTTP協議和服務器交互主要是進行數據的提交,通常數據的提交是通過 GET 和 POST 兩種方式來完成,

C# HttpWebRequest提交數據方式

1. GET 方式。 
GET 方式通過在網絡地址附加參數來完成數據的提交,比如在地址 http://www.google.com/webhp?hl=zh-CN 中,前面部分 http://www.google.com/webhp 表示數據提交的網址,后面部分 hl=zh-CN 表示附加的參數,其中 hl 表示一個鍵(key), zh-CN 表示這個鍵對應的值(value)。程序代碼如下:

HttpWebRequest req =  
(HttpWebRequest)HttpWebRequest.Create("http://www.google.com/webhp?hl=zh-CN" ); 
req.Method = "GET"; 
using (WebResponse wr = req.GetResponse()) 
{ 
   //在這里對接收到的頁面內容進行處理 
}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7

2. POST 方式。

POST 方式通過在頁面內容中填寫參數的方法來完成數據的提交,參數的格式和 GET 方式一樣,是類似於 hl=zh-CN&newwindow=1 這樣的結構。程序代碼如下:

string param = "hl=zh-CN&newwindow=1";        //參數
byte[] bs = Encoding.ASCII.GetBytes(param);    //參數轉化為ascii碼
HttpWebRequest req = (HttpWebRequest) HttpWebRequest.Create("http://www.google.com/intl/zh-CN/" );  //創建request
req.Method = "POST";    //確定傳值的方式,此處為post方式傳值
req.ContentType = "application/x-www-form-urlencoded"; 
req.ContentLength = bs.Length; 
using (Stream reqStream = req.GetRequestStream()) 
{ 
   reqStream.Write(bs, 0, bs.Length); 
} 
using (WebResponse wr = req.GetResponse()) 
{ 
   //在這里對接收到的頁面內容進行處理 
} 
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14

3. 使用 GET 方式提交中文數據。

GET 方式通過在網絡地址中附加參數來完成數據提交,對於中文的編碼,常用的有 gb2312 和 utf8 兩種,用 gb2312 方式編碼訪問的程序代碼如下:

Encoding myEncoding = Encoding.GetEncoding("gb2312");     //確定用哪種中文編碼方式
string address = "http://www.baidu.com/s?"+ HttpUtility.UrlEncode("參數一", myEncoding) +  "=" + HttpUtility.UrlEncode("值一", myEncoding);       //拼接數據提交的網址和經過中文編碼后的中文參數
HttpWebRequest req =   (HttpWebRequest)HttpWebRequest.Create(address);  //創建request
req.Method = "GET";    //確定傳值方式,此處為get方式
using (WebResponse wr = req.GetResponse()) 
{ 
   //在這里對接收到的頁面內容進行處理 
} 
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8

在上面的程序代碼中,我們以 GET 方式訪問了網址 http://www.baidu.com/s ,傳遞了參數“參數一=值一”,由於無法告知對方提交數據的編碼類型,所以編碼方式要以對方的網站為標准。常見的網站中, www.baidu.com (百度)的編碼方式是 gb2312, www.google.com (谷歌)的編碼方式是 utf8。

4. 使用 POST 方式提交中文數據。

POST 方式通過在頁面內容中填寫參數的方法來完成數據的提交,由於提交的參數中可以說明使用的編碼方式,所以理論上能獲得更大的兼容性。用 gb2312 方式編碼訪問的程序代碼如下:

Encoding myEncoding = Encoding.GetEncoding("gb2312"); //確定中文編碼方式。此處用gb2312
string param =   HttpUtility.UrlEncode("參數一", myEncoding) +   "=" + HttpUtility.UrlEncode("值一", myEncoding) +   "&" +     HttpUtility.UrlEncode("參數二", myEncoding) +  "=" + HttpUtility.UrlEncode("值二", myEncoding); 
byte[] postBytes = Encoding.ASCII.GetBytes(param); //將參數轉化為assic碼
HttpWebRequest req = (HttpWebRequest)  HttpWebRequest.Create( "http://www.baidu.com/s" ); 
req.Method = "POST"; 
req.ContentType =   "application/x-www-form-urlencoded;charset=gb2312"; 
req.ContentLength = postBytes.Length; 
using (Stream reqStream = req.GetRequestStream()) 
{ 
   reqStream.Write(bs, 0, bs.Length); 
} 
using (WebResponse wr = req.GetResponse()) 
{ 
   //在這里對接收到的頁面內容進行處理 
}  
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15

從上面的代碼可以看出, POST 中文數據的時候,先使用 UrlEncode 方法將中文字符轉換為編碼后的 ASCII 碼,然后提交到服務器,提交的時候可以說明編碼的方式,用來使對方服務器能夠正確的解析。

以上列出了客戶端程序使用HTTP協議與服務器交互的情況,常用的是 GET 和 POST 方式。

現在流行的 WebService 也是通過 HTTP 協議來交互的,使用的是 POST 方法。與以上稍有所不同的是, WebService 提交的數據內容和接收到的數據內容都是使用了 XML 方式編碼。所以, HttpWebRequest 也可以使用在調用 WebService 的情況下。

C# HttpWebRequest提交數據方式的基本內容就向你介紹到這里,希望對你了解和學習C# HttpWebRequest提交數據方式有所幫助。

    #region 公共方法
    /// <summary>
    /// Get數據接口
    /// </summary>
    /// <param name="getUrl">接口地址</param>
    /// <returns></returns>
    private static string GetWebRequest(string getUrl)
    {
        string responseContent = "";

        HttpWebRequest request = (HttpWebRequest)WebRequest.Create(getUrl);
        request.ContentType = "application/json";
        request.Method = "GET";

        HttpWebResponse response = (HttpWebResponse)request.GetResponse();
        //在這里對接收到的頁面內容進行處理
        using (Stream resStream = response.GetResponseStream())
        {
            using (StreamReader reader = new StreamReader(resStream, Encoding.UTF8))
            {
                responseContent = reader.ReadToEnd().ToString();
            }
        }
        return responseContent;
    }
    /// <summary>
    /// Post數據接口
    /// </summary>
    /// <param name="postUrl">接口地址</param>
    /// <param name="paramData">提交json數據</param>
    /// <param name="dataEncode">編碼方式(Encoding.UTF8)</param>
    /// <returns></returns>
    private static string PostWebRequest(string postUrl, string paramData, Encoding dataEncode)
    {
        string responseContent = string.Empty;
        try
        {
            byte[] byteArray = dataEncode.GetBytes(paramData); //轉化
            HttpWebRequest webReq = (HttpWebRequest)WebRequest.Create(new Uri(postUrl));
            webReq.Method = "POST";
            webReq.ContentType = "application/x-www-form-urlencoded";
            webReq.ContentLength = byteArray.Length;
            using (Stream reqStream = webReq.GetRequestStream())
            {
                reqStream.Write(byteArray, 0, byteArray.Length);//寫入參數
                                                                //reqStream.Close();
            }
            using (HttpWebResponse response = (HttpWebResponse)webReq.GetResponse())
            {
                //在這里對接收到的頁面內容進行處理
                using (StreamReader sr = new StreamReader(response.GetResponseStream(), Encoding.Default))
                {
                    responseContent = sr.ReadToEnd().ToString();
                }
            }
        }
        catch (Exception ex)
        {
            return ex.Message;
        }
        return responseContent;
    }

    #endregion
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  • 32
  • 33
  • 34
  • 35
  • 36
  • 37
  • 38
  • 39
  • 40
  • 41
  • 42
  • 43
  • 44
  • 45
  • 46
  • 47
  • 48
  • 49
  • 50
  • 51
  • 52
  • 53
  • 54
  • 55
  • 56
  • 57
  • 58
  • 59
  • 60
  • 61
  • 62
  • 63
  • 64

OAuth頭部

//構造OAuth頭部 
StringBuilder oauthHeader = new StringBuilder();
oauthHeader.AppendFormat("OAuth realm=\"\", oauth_consumer_key={0}, ", apiKey);
oauthHeader.AppendFormat("oauth_nonce={0}, ", nonce);
oauthHeader.AppendFormat("oauth_timestamp={0}, ", timeStamp);
oauthHeader.AppendFormat("oauth_signature_method={0}, ", "HMAC-SHA1");
oauthHeader.AppendFormat("oauth_version={0}, ", "1.0");
oauthHeader.AppendFormat("oauth_signature={0}, ", sig);
oauthHeader.AppendFormat("oauth_token={0}", accessToken);

//構造請求 
StringBuilder requestBody = new StringBuilder("");
Encoding encoding = Encoding.GetEncoding("utf-8");
byte[] data = encoding.GetBytes(requestBody.ToString());

// Http Request的設置 
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(uri);
request.Headers.Set("Authorization", oauthHeader.ToString());
//request.Headers.Add("Authorization", authorization); 
request.ContentType = "application/atom+xml";
request.Method = "GET";
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21

C#通過WebClient/HttpWebRequest實現http的post/get方法

1.POST方法(httpWebRequest)

//body是要傳遞的參數,格式"roleId=1&uid=2"
//post的cotentType填寫:"application/x-www-form-urlencoded"
//soap填寫:"text/xml; charset=utf-8"
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;
}


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM