【C#随手记】实现调用Http的Post请求的简单记录

    /// <summary>
    /// Post请求
    /// </summary>
    /// <param name="url">url</param>
    /// <param name="postPar">需要的参数 例如:"Name=Ning&Age=18"</param>
    /// <returns>字符串</returns>
    public static string Post(string url, string postPar = null)
    {
    
    
        #region 构造一个“HttpWebRequest”
        HttpWebRequest httpWebRequest = (HttpWebRequest)WebRequest.Create(url);//WebRequest.Creat(requestUriString)创建一个Web请求
        httpWebRequest.Method = "POST";//-----------------------------设置HttpWebRequest的Method属性的时候,字符串要全大写
        httpWebRequest.ContentType = "application/x-www-form-urlencoded";//死记下来
        #endregion

        if (postPar == null)//如果不需要传参,直接返回返回响应内容
            goto GetResponse;

        #region 将参数转为字节组写入 “需求流”
        byte[] postConByte = Encoding.Default.GetBytes(postPar);
        httpWebRequest.ContentLength = postConByte.Length;
        using (Stream stream = httpWebRequest.GetRequestStream())
            stream.Write(postConByte, 0, postConByte.Length);
        #endregion

        GetResponse:
        {
    
    
            #region 从“响应流”里读取结果
            HttpWebResponse httpWebResponse = (HttpWebResponse)httpWebRequest.GetResponse();
            using (Stream responseStream = httpWebResponse.GetResponseStream())
            {
    
    
                StreamReader streamReader = new StreamReader(responseStream);
                string postResult = streamReader.ReadToEnd();
                return postResult;
            }
            #endregion
        }
    }

需要引用的命名空间

using System.Net;
using System.Text;
using System.IO;


个人笔记 仅供参考 欢迎指正

猜你喜欢

转载自blog.csdn.net/m0_55907341/article/details/123171264