C# 后端post的请求方法

Posted 巫威

tags:

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

C# 模拟post请求方法

方法1:

/// <summary>
        /// 模拟Post请求
        /// </summary>
        /// <param name="url">地址</param>
        /// <param name="postDataStr">参数:a=123&b=www</param>
        /// <returns></returns>
        public string HttpPost(string url, string postDataStr)
        {
            Encoding encode = System.Text.Encoding.GetEncoding("utf-8");
            byte[] arrB = encode.GetBytes(postDataStr);
            HttpWebRequest myReq = (HttpWebRequest)WebRequest.Create(url);
            myReq.Method = "POST";
            myReq.ContentType = "application/x-www-form-urlencoded";
            myReq.ContentLength = arrB.Length;
            Stream outStream = myReq.GetRequestStream();
            outStream.Write(arrB, 0, arrB.Length);
            outStream.Close();


            //接收HTTP做出的响应
            WebResponse myResp = myReq.GetResponse();
            Stream ReceiveStream = myResp.GetResponseStream();
            StreamReader readStream = new StreamReader(ReceiveStream, encode);
            Char[] read = new Char[256];
            int count = readStream.Read(read, 0, 256);
            string str = null;
            while (count > 0)
            {
                str += new String(read, 0, count);
                count = readStream.Read(read, 0, 256);
            }
            readStream.Close();
            myResp.Close();

            return str;
        }

方法2:

/// <summary>
    /// 发送POST请求
    /// </summary>
    /// <param name="url"></param>
    /// <param name="postDataStr"></param>
    /// <returns></returns>
    public static string HttpPost(string url, string postDataStr)
    {
        HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
        request.Method = "POST";
        request.ContentType = "application/x-www-form-urlencoded";
        request.ContentLength = Encoding.UTF8.GetByteCount(postDataStr);
        Stream myRequestStream = request.GetRequestStream();
        StreamWriter myStreamWriter = new StreamWriter(myRequestStream, Encoding.GetEncoding("gb2312"));
        myStreamWriter.Write(postDataStr);
        myStreamWriter.Close();

        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;
    }

  

 

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

vue中使用axios处理post方法导出excel表格(后端返回文件流)

.NET httpClient Post请求,GET请求方法

.Net(C#)后台发送Get和Post请求的几种方法总结

C# 执行基本的 Web POST 请求

C#调用百度API方法,POST和GET请求

C#获取POST请求发来的数据