服務端發post請求產生的編碼問題

最近在作一個功能,大概功能是這樣的,供應商提供http接口給咱們,而後咱們抓取供應商的數據保存到數據庫,問題在於他們編碼格式是gb2312的,而咱們是utf-8。前端

你們可能會有個誤區,post請求是無需編碼的,其實否則,只要在http請求頭中 "Content-Type"爲"application/x-www-form-urlencoded,調接口前都會用當前編碼格式urlencode。因此若是前端post數據到後端時,前端是gb2312編碼格式,後端是utf-8,只需在Content-Type中設置,application/x-www-form-urlencoded;charset=utf-8。web

而咱們是服務端直接調接口,而我用的是restsharp數據庫

var request = new RestRequest(Method.POST);

request.RequestFormat = DataFormat.Json;
request.AddBody(model);

var client = new RestClient("http://localhost:2290/Interface/Index");

var response = client.Execute(request);
return response.Content;

翻閱文檔,這期間會自動urlencode。。。json

後來嘗試設置web.config,設置默認編碼格式,編碼問題依然解決不了,有種衝動想去看restsharp的源碼,惋惜時間來不及啊。。。。(有時間必定要看下)後端

<globalization requestEncoding="gb2312" responseEncoding="gb2312"/>

最後終於找到了解決方案,用.net 源生的方式 httprequest 瀏覽器

        /// <summary>  
        /// 建立POST方式的HTTP請求  
        /// </summary>  
        /// <param name="url">請求的URL</param>  
        /// <param name="parameters">隨同請求POST的參數名稱及參數值字典</param>  
        /// <param name="timeout">請求的超時時間</param>  
        /// <param name="userAgent">請求的客戶端瀏覽器信息,能夠爲空</param>  
        /// <param name="requestEncoding">發送HTTP請求時所用的編碼</param>  
        /// <param name="cookies">隨同HTTP請求發送的Cookie信息,若是不須要身份驗證能夠爲空</param>  
        /// <returns></returns>  
        public static HttpWebResponse CreatePostHttpResponse(string url, IDictionary<string, string> parameters, int? timeout, string userAgent, Encoding requestEncoding, CookieCollection cookies)
        {
            if (string.IsNullOrEmpty(url))
            {
                throw new ArgumentNullException("url");
            }
            if (requestEncoding == null)
            {
                throw new ArgumentNullException("requestEncoding");
            }
            HttpWebRequest request = null;
            //若是是發送HTTPS請求  
            if (url.StartsWith("https", StringComparison.OrdinalIgnoreCase))
            {
                ServicePointManager.ServerCertificateValidationCallback = new RemoteCertificateValidationCallback(CheckValidationResult);
                request = WebRequest.Create(url) as HttpWebRequest;
                request.ProtocolVersion = HttpVersion.Version10;
            }
            else
            {
                request = WebRequest.Create(url) as HttpWebRequest;
            }
            request.Method = "POST";
            request.ContentType = "application/x-www-form-urlencoded";

            if (!string.IsNullOrEmpty(userAgent))
            {
                request.UserAgent = userAgent;
            }
            else
            {
                request.UserAgent = DefaultUserAgent;
            }

            if (timeout.HasValue)
            {
                request.Timeout = timeout.Value;
            }
            if (cookies != null)
            {
                request.CookieContainer = new CookieContainer();
                request.CookieContainer.Add(cookies);
            }
            //若是須要POST數據  
            if (!(parameters == null || parameters.Count == 0))
            {
                StringBuilder buffer = new StringBuilder();
                int i = 0;
                foreach (string key in parameters.Keys)
                {
                    if (i > 0)
                    {
                        buffer.AppendFormat("&{0}={1}", key, parameters[key]);
                    }
                    else
                    {
                        buffer.AppendFormat("{0}={1}", key, parameters[key]);
                    }
                    i++;
                }
                byte[] data = requestEncoding.GetBytes(buffer.ToString());
                using (Stream stream = request.GetRequestStream())
                {
                    stream.Write(data, 0, data.Length);
                }
            }
            return request.GetResponse() as HttpWebResponse;
        }

調用以下:cookie

            IDictionary<string, string> parameters = new Dictionary<string, string>();
            parameters.Add("RequestJson", jsonstr);

            HttpWebResponse response = HttpWebResponseUtility.CreatePostHttpResponse(url, parameters, null, null, Encoding.GetEncoding("GB2312"), null);

            using (StreamReader reader = new StreamReader(response.GetResponseStream(), System.Text.Encoding.UTF8))
            {
                strres = reader.ReadToEnd();
            }
相關文章
相關標籤/搜索