c#發送http請求注意

這裏要注意幾個點:
第一就是編碼,若是編碼不對,容易中文亂碼
第二就是ContentType 若是設置不對,有可能連方法都調試不進去(我api用的是MVC的普通controller)
第三就是paramData參數形式要與ContentType保持一致web

        /// <summary>
        /// 發送POST請求
        /// </summary>
        /// <param name="postUrl">api</param>
        /// <param name="paramData">參數,通常是param1=1&m2=2這種形式</param>
        /// <param name="dataEncode">編碼</param>
        /// <returns></returns>
        private string PostWebRequest(string postUrl, string paramData, Encoding dataEncode)
        {
            string ret = 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.ContentType = "application/json";
                webReq.ContentLength = byteArray.Length;
                Stream newStream = webReq.GetRequestStream();
                newStream.Write(byteArray, 0, byteArray.Length);//寫入參數
                newStream.Close();
                HttpWebResponse response = (HttpWebResponse)webReq.GetResponse();
                StreamReader sr = new StreamReader(response.GetResponseStream(), Encoding.UTF8);
                ret = sr.ReadToEnd();
                sr.Close();
                response.Close();
                newStream.Close();
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
            return ret;
        }
相關文章
相關標籤/搜索