C# Http请求封装(简易版)

分类:C#     发布:2019-08-16     来源:本站     浏览:790 次
using System;
using System.IO;
using System.Net;
using System.Text;

namespace RC.Framework.Helper
{
    public class HttpHelper
    {
        public static string HttpGet(string url, string data)
        {
            var request = (HttpWebRequest)WebRequest.Create(url + (data == "" ? "" : "?") + data);
            request.Method = "GET";
            request.ContentType = "text/html;";
            using (var response = (HttpWebResponse)request.GetResponse())
            {
                var stream = response.GetResponseStream();
                string s = null;
                if (stream != null)
                {
                    using (var reader = new StreamReader(stream, Encoding.UTF8))
                    {
                        s = reader.ReadToEnd();
                        reader.Close();
                    }
                    stream.Close();
                }
                return s;
            }
        }

        public static string HttpPost(string url, string data)
        {
            try
            {
                var byteArray = Encoding.UTF8.GetBytes(data);
                var request = (HttpWebRequest)WebRequest.Create(new Uri(url));
                request.Method = "post";
                request.ContentType = "application/x-www-form-urlencoded";
                request.ContentLength = byteArray.Length;
                request.Timeout = 5 * 60 * 1000;
                using (var stream = request.GetRequestStream())
                {
                    stream.Write(byteArray, 0, byteArray.Length);
                    stream.Close();
                }
                string res;
                using (var response = (HttpWebResponse)request.GetResponse())
                {
                    res = new StreamReader(response.GetResponseStream(), Encoding.Default).ReadToEnd();
                }
                return res;
            }
            catch (Exception ex)
            {
                return ex.Message + ex.StackTrace;
            }
        }
    }
}
        

如果觉得文章对您有帮助,您可以对我进行打赏 ¥0.88 元(金额随机^_^,每次刷新金额不同)。

请使用支付宝扫码支付

留言评论

*称  呼:
*联系方式: 方便与您取得联系,推荐使用邮箱。
*内  容:

已有评论

暂无数据

上一篇:SQL Server 查询最近执行过的SQL语句(用于排查执行耗时语句)

下一篇:C# Http请求封装(携带cookie版)(用于模拟登录)