HTTP请求方法

Posted 妖狐鬼魅

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了HTTP请求方法相关的知识,希望对你有一定的参考价值。

 #region HTTP请求方法
        public string HttpPost(string Url, string postDataStr = "", string access_token = "")
        {

            //CookieContainer cookie = new CookieContainer();


            HttpWebRequest request = (HttpWebRequest)WebRequest.Create(Url);
            if (!string.IsNullOrWhiteSpace(access_token))
            {

                request.Headers.Add("Authorization", access_token);
            }
            request.Method = "POST";
            request.ContentType = "application/json;charset=utf-8";

            if (!string.IsNullOrWhiteSpace(postDataStr))
            {
                request.ContentLength = Encoding.UTF8.GetByteCount(postDataStr);
            }

            //request.CookieContainer = cookie;
            Stream myRequestStream = request.GetRequestStream();
            StreamWriter myStreamWriter = new StreamWriter(myRequestStream, Encoding.GetEncoding("gb2312"));
            //StreamWriter myStreamWriter = new StreamWriter(myRequestStream, Encoding.GetEncoding("utf-8"));
            if (!string.IsNullOrWhiteSpace(postDataStr))
            {
                myStreamWriter.Write(postDataStr);
            }
            myStreamWriter.Close();

            HttpWebResponse response = (HttpWebResponse)request.GetResponse();

            //response.Cookies = cookie.GetCookies(response.ResponseUri);
            Stream myResponseStream = response.GetResponseStream();
            StreamReader myStreamReader = new StreamReader(myResponseStream, Encoding.GetEncoding("utf-8"));
            string retString = myStreamReader.ReadToEnd();
            myStreamReader.Close();
            myResponseStream.Close();

            return retString;
        }

        public string HttpGet(string Url, string postDataStr = "", string access_token = "")
        {
            HttpWebRequest request = (HttpWebRequest)WebRequest.Create(Url + (postDataStr == "" ? "" : "?") + postDataStr);
            request.Method = "GET";
            request.ContentType = "text/html;charset=UTF-8";
            if (!string.IsNullOrWhiteSpace(access_token))
            {

                request.Headers.Add("Authorization", access_token);
            }

            HttpWebResponse response = (HttpWebResponse)request.GetResponse();
            Stream myResponseStream = response.GetResponseStream();
            StreamReader myStreamReader = new StreamReader(myResponseStream, Encoding.GetEncoding("utf-8"));
            string retString = myStreamReader.ReadToEnd();
            myStreamReader.Close();
            myResponseStream.Close();

            return retString;
        }

        #endregion

 

以上是关于HTTP请求方法的主要内容,如果未能解决你的问题,请参考以下文章

postman 自动生成 curl 代码片段

如何对媒体片段的任何部分进行范围请求?

从Salesforce到Taleo的基本HTTP身份验证

VSCode自定义代码片段14——Vue的axios网络请求封装

VSCode自定义代码片段14——Vue的axios网络请求封装

VSCode自定义代码片段14——Vue的axios网络请求封装