首页 > 其他分享 >WebForm之企业微信开发(1)——准备httphelper

WebForm之企业微信开发(1)——准备httphelper

时间:2023-03-28 13:49:21浏览次数:33  
标签:string 微信 httphelper request WebForm var null response requestStream

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

    public class HttpHelper
    {
        /// <summary>
        /// 发起一个HTTP请求(以POST同步方式)
        /// </summary>
        /// <param name="url">请求地址</param>
        /// <param name="param">参数:json格式字符串</param>
        public static string HttpPost(string url, string param = "")
        {
            var request = (HttpWebRequest)WebRequest.Create(url);
            request.Method = "POST";
            request.ContentType = "application/json";
            request.Accept = "*/*";
            request.Timeout = 10000;
            request.AllowAutoRedirect = false;
            StreamWriter requestStream = null;
            WebResponse response = null;
            string responseStr = null;
            try
            {
                requestStream = new StreamWriter(request.GetRequestStream());
                requestStream.Write(param);
                requestStream.Close();
                response = request.GetResponse();
                if (response != null)
                {
                    var reader = new StreamReader(response.GetResponseStream(), Encoding.UTF8);
                    responseStr = reader.ReadToEnd();
                    reader.Close();
                }
            }
            catch (Exception e)
            {
                throw e;
            }
            finally
            {
                request = null;
                requestStream = null;
                response = null;
            }
            return responseStr;
        }

        /// <summary>
        /// get请求,同步方式
        /// </summary>
        public static string HttpGet(string url, string postDataStr)
        {
            var request = (HttpWebRequest)WebRequest.Create(url + (postDataStr == "" ? "" : "?") + postDataStr);
            request.Method = "GET";
            request.ContentType = "text/html;charset=UTF-8";

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

            return retString;
        }

    }

 

翻译

搜索

复制

标签:string,微信,httphelper,request,WebForm,var,null,response,requestStream
From: https://www.cnblogs.com/liangguangqing/p/17264826.html

相关文章