• C#后台 Get、Post 网络请求


     1.Post、Get请求

    public static string HttpPost(string url, string param)
            {
                HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create(url);
                request.Method = "POST";
                request.ContentType = "application/x-www-form-urlencoded";
                request.Accept = "*/*";
                request.Timeout = 15000;
                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)
                    {
                        StreamReader reader = new StreamReader(response.GetResponseStream(), Encoding.UTF8);
                        responseStr = reader.ReadToEnd();
                        reader.Close();
                    }
                }
                catch (Exception)
                {
                    throw;
                }
                finally
                {
                    request = null;
                    requestStream = null;
                    response = null;
                }
    
                return responseStr;
            }
    Post提交
    public static string HttpPost(string url, string param)
            {
                HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create(url);
                request.Method = "POST";
                request.ContentType = "application/x-www-form-urlencoded";
                request.Accept = "*/*";
                request.Timeout = 15000;
                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)
                    {
                        StreamReader reader = new StreamReader(response.GetResponseStream(), Encoding.UTF8);
                        responseStr = reader.ReadToEnd();
                        reader.Close();
                    }
                }
                catch (Exception)
                {
                    throw;
                }
                finally
                {
                    request = null;
                    requestStream = null;
                    response = null;
                }
    
                return responseStr;
            }
    Get提交

    微信公众平台调用post提交数据 有些需要传递json格式的数据如果不是json格式的数据可能会报错

    2.简单的示例代码

    /// <summary>
            /// 将字典类型序列化为json字符串
            /// </summary>
            /// <typeparam name="TKey">字典key</typeparam>
            /// <typeparam name="TValue">字典value</typeparam>
            /// <param name="dict">要序列化的字典数据</param>
            /// <returns>json字符串</returns>
            public static string SerializeDictionaryToJsonString<TKey, TValue>(Dictionary<TKey, TValue> dict)
            {
                if (dict.Count == 0)
                    return "";
    
                string jsonStr = JsonConvert.SerializeObject(dict);
                return jsonStr;
            }
    简单的将字典类型序列化为json字符串
    public ActionResult Index()
    {
                Dictionary<string, string> list = new Dictionary<string, string>();
                list.Add("begin_date", "2014-12-07");
                list.Add("end_date", "2014-12-07");
                //用户分析数据接口  开始没有传递json格式的数据 总是报日期格式不正确 简单的写了个json转换的
                var str = Utils.HttpPost("https://api.weixin.qq.com/datacube/getusersummary?access_token=xxxxxxxx", SerializeDictionaryToJsonString(list));
    
                return View();
    }    
    用户分析数据接口

    3.获取网页信息--可以做到一个文件多出使用(后台结果公告内容,通过获取结果公告内容抓取到前台显示)

    #region 获取网页信息
            #region 根据URL地址获取信息GET
    
            public static String GetResult(string url)
            {
                return GetResult(url, Encoding.Default);
            }
            #endregion
    
            #region 根据URL地址获取对应编码信息
            public static String GetResult(string url, Encoding encoding)
            {
                try
                {
    
                    var webRequest = (HttpWebRequest)WebRequest.Create(url);
                    //获取响应结果 
                    var webResponse = (HttpWebResponse)webRequest.GetResponse();
                    //获取响应流
                    Stream stream = webResponse.GetResponseStream();
                    using (StreamReader streamReader = new StreamReader(stream, encoding))
                    {
                        string result = String.Empty;
                        result = streamReader.ReadToEnd();
                        streamReader.Close();
                        webResponse.Close();
                        webRequest.Abort();
                        return result;
                    }
                }
                catch (Exception ex)
                {
                    return "-1";
                    //return ex.Message.Length > 100 ? ex.Message.Substring(0, 100) : ex.Message; 
                }
            }
            #endregion
            #endregion
    获取网页信息
    /// <summary>
        /// 获取并截取HTML源码
        /// </summary>
        /// <param name="strUrl"></param>
        /// <returns></returns>
        public static string GetUrlAndCutSourceHtml(string strUrl)
        { 
            string strTemp = Common.GetResult(strUrl, System.Text.Encoding.GetEncoding("utf-8"));
            if (!strTemp.Equals("-1"))
            {
                strTemp = strTemp.Substring(strTemp.IndexOf("<!--begin-->"));
                strTemp = strTemp.Substring(0, strTemp.IndexOf("<!--end-->"));
            }
            return strTemp;
        }
    获取之间的内容
    <body>
        <form>
            <!--begin-->
            <div>
                显示的内容
                显示的内容
                显示的内容
                显示的内容
                显示的内容
                显示的内容
                显示的内容
                显示的内容
                显示的内容
                显示的内容
                显示的内容
            </div>
            <!--end-->
        </form>
    </body>
    </html>
    html页面
  • 相关阅读:
    mkimage command not found
    Linux添加快捷启动方式 (Ubuntu Debian CentOS)
    CentOS下通过locale来设置字符集
    CentOS 安装中文输入法
    Centos 安装KScope1.6.2
    centos 配置NFS服务器
    Linux shell判断文件和文件夹是否存在
    数据库中Schema和Database有什么区别
    配置Tomcat使用https协议
    HTML font: 12px/1.5 Arial; 是什么意思
  • 原文地址:https://www.cnblogs.com/lovable/p/9186889.html
Copyright © 2020-2023  润新知