c#-post请求实例

2024-04-23 18:20:23 浏览数 (1)

通过http进行post请求获得json数据,并将HttpWebResponse返回结果转换为string

代码语言:javascript复制
        /// <summary>
        /// 向指定URL发送HTTP请求POST
        /// </summary>
        /// <param name="url">目标资源路径</param>
        /// <param name="jsonBody">json内容</param>
        /// <returns></returns>
        public static string doPostMethod(string url, string jsonBody)
        {
            HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
            request.Method = "post";
            request.ContentType = "application/json;";
            request.KeepAlive = false;
            request.ProtocolVersion = HttpVersion.Version10;
            var stream = request.GetRequestStream();
            using (var writer = new StreamWriter(stream))
            {
                writer.Write(jsonBody);
                writer.Flush();
            }
            stream.Close();
            HttpWebResponse response = null;
            string json = string.Empty;

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

            return json;
        }

        /// <summary>
        /// 将 HttpWebResponse 返回结果转换成 string
        /// </summary>
        /// <param name="response">服务器响应</param>
        /// <returns>服务器返回数据JSON</returns>
        private static string getResponseString(HttpWebResponse response)
        {
            string json = null;
            using (StreamReader reader = new StreamReader(response.GetResponseStream(), System.Text.Encoding.GetEncoding("UTF-8")))
            {
                json = reader.ReadToEnd();
            }
            return json;
        }

0 人点赞