千家信息网

C#怎么发送Get、Post请求

发表于:2024-11-20 作者:千家信息网编辑
千家信息网最后更新 2024年11月20日,这篇文章主要讲解了"C#怎么发送Get、Post请求",文中的讲解内容简单清晰,易于学习与理解,下面请大家跟着小编的思路慢慢深入,一起来研究和学习"C#怎么发送Get、Post请求"吧!目录Get请求
千家信息网最后更新 2024年11月20日C#怎么发送Get、Post请求

这篇文章主要讲解了"C#怎么发送Get、Post请求",文中的讲解内容简单清晰,易于学习与理解,下面请大家跟着小编的思路慢慢深入,一起来研究和学习"C#怎么发送Get、Post请求"吧!

目录
  • Get请求

  • Post请求

Get请求

1.简单发送Get请求

/// /// 指定Url地址使用Get 方式获取全部字符串/// /// 请求链接地址/// public static string Get(string url){    string result = "";    HttpWebRequest req = (HttpWebRequest)WebRequest.Create(url);    HttpWebResponse resp = (HttpWebResponse)req.GetResponse();    Stream stream = resp.GetResponseStream();    try    {        //获取内容        using (StreamReader reader = new StreamReader(stream))        {            result = reader.ReadToEnd();        }    }    finally    {        stream.Close();    }    return result;}

2.带请求参数的Get方法

/// /// 发送Get请求/// /// 地址/// 请求参数定义/// public static string Get(string url, Dictionary dic){    string result = "";    StringBuilder builder = new StringBuilder();    builder.Append(url);    if (dic.Count > 0)    {        builder.Append("?");        int i = 0;        foreach (var item in dic)        {            if (i > 0)                builder.Append("&");            builder.AppendFormat("{0}={1}", item.Key, item.Value);            i++;        }    }    HttpWebRequest req = (HttpWebRequest)WebRequest.Create(builder.ToString());    //添加参数    HttpWebResponse resp = (HttpWebResponse)req.GetResponse();    Stream stream = resp.GetResponseStream();    try    {        //获取内容        using (StreamReader reader = new StreamReader(stream))        {            result = reader.ReadToEnd();        }    }    finally    {        stream.Close();    }    return result;}

3.自定义指定Http请求头,自定义指定编码解析返回结果

HttpWebRequest req = (HttpWebRequest)WebRequest.Create(url);req.Method = "GET";req.Headers["Accept-Language"] = "zh-CN,zh;q=0.8";req.Referer = "https://www.baidu.com/";HttpWebResponse resp = (HttpWebResponse)req.GetResponse();Stream stream = resp.GetResponseStream();string result = "";//注意,此处使用的编码是:gb2312//using (StreamReader reader = new StreamReader(stream, Encoding.Default))using (StreamReader reader = new StreamReader(stream, Encoding.GetEncoding("gb2312"))){    result = reader.ReadToEnd();}

Post请求

此处内容传输都是用UTF-8编码

1.不带参数发送Post请求

///         /// 指定Post地址使用Get 方式获取全部字符串        ///         /// 请求后台地址        ///         public static string Post(string url)        {            string result = "";            HttpWebRequest req = (HttpWebRequest)WebRequest.Create(url);            req.Method = "POST";            HttpWebResponse resp = (HttpWebResponse)req.GetResponse();            Stream stream = resp.GetResponseStream();            //获取内容            using (StreamReader reader = new StreamReader(stream, Encoding.UTF8))            {                result = reader.ReadToEnd();            }            return result;        }

2.带参数Post请求,指定键值对

///         /// 指定Post地址使用Get 方式获取全部字符串        ///         /// 请求后台地址        ///         public static string Post(string url,Dictionary dic)        {            string result = "";            HttpWebRequest req = (HttpWebRequest)WebRequest.Create(url);            req.Method = "POST";            req.ContentType = "application/x-www-form-urlencoded";            #region 添加Post 参数            StringBuilder builder = new StringBuilder();            int i = 0;            foreach (var item in dic)            {                if (i > 0)                    builder.Append("&");                builder.AppendFormat("{0}={1}", item.Key, item.Value);                i++;            }            byte[] data = Encoding.UTF8.GetBytes(builder.ToString());            req.ContentLength = data.Length;            using (Stream reqStream = req.GetRequestStream())            {                reqStream.Write(data, 0, data.Length);                reqStream.Close();            }            #endregion            HttpWebResponse resp = (HttpWebResponse)req.GetResponse();            Stream stream = resp.GetResponseStream();            //获取响应内容            using (StreamReader reader = new StreamReader(stream, Encoding.UTF8))            {                result = reader.ReadToEnd();            }            return result;        }

3.带参数的Post请求,指定发送字符串内容

/// /// 指定Post地址使用Get 方式获取全部字符串/// /// 请求后台地址/// Post提交数据内容(utf-8编码的)/// public static string Post(string url, string content){    string result = "";    HttpWebRequest req = (HttpWebRequest)WebRequest.Create(url);    req.Method = "POST";    req.ContentType = "application/x-www-form-urlencoded";     #region 添加Post 参数    byte[] data = Encoding.UTF8.GetBytes(content);    req.ContentLength = data.Length;    using (Stream reqStream = req.GetRequestStream())    {        reqStream.Write(data, 0, data.Length);        reqStream.Close();    }    #endregion     HttpWebResponse resp = (HttpWebResponse)req.GetResponse();    Stream stream = resp.GetResponseStream();    //获取响应内容    using (StreamReader reader = new StreamReader(stream, Encoding.UTF8))    {        result = reader.ReadToEnd();    }    return result;}

转载方法:

 HttpWebRequest req = (HttpWebRequest)HttpWebRequest.Create("http://fanyi.baidu.com/transcontent");            Encoding encoding = Encoding.UTF8;            string param = "ie=utf-8&source=txt&query=hello&t=1327829764203&token=8a7dcbacb3ed72cad9f3fb079809a127&from=auto&to=auto";            //encoding.GetBytes(postData);            byte[] bs = Encoding.ASCII.GetBytes(param);            string responseData = String.Empty;                        req.Method = "POST";            req.ContentType = "application/x-www-form-urlencoded";            req.ContentLength = bs.Length;            using (Stream reqStream = req.GetRequestStream())            {                reqStream.Write(bs, 0, bs.Length);                reqStream.Close();            }            using (HttpWebResponse response = (HttpWebResponse)req.GetResponse())            {                using (StreamReader reader = new StreamReader(response.GetResponseStream(),encoding))                {                    responseData = reader.ReadToEnd().ToString();                }                context.Response.Write(responseData);            }

感谢各位的阅读,以上就是"C#怎么发送Get、Post请求"的内容了,经过本文的学习后,相信大家对C#怎么发送Get、Post请求这一问题有了更深刻的体会,具体使用情况还需要大家实践验证。这里是,小编将为大家推送更多相关知识点的文章,欢迎关注!

0