前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >C# 实现对网站Get与Post请求

C# 实现对网站Get与Post请求

作者头像
微软技术分享
发布2022-12-28 18:07:48
6870
发布2022-12-28 18:07:48

通过配合new WebClient()自己封装接口HttpGetPage(string url,string coding)用户传入网站地址以及编码方式,即可下载指定页面到变量中。

代码语言:javascript
复制
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Text;

namespace ConsoleApplication1
{
    class Program
    {
        public static string HttpGetPage(string url,string coding)
        {
            string pageHtml = string.Empty;
            try
            {
                using(WebClient MyWebClient = new WebClient())
                {
                    Encoding encode = Encoding.GetEncoding(coding);
                    MyWebClient.Headers.Add("User-Agent", "Mozilla/5.0 (Windows NT 10.0; WOW64)AppleWebKit/537.36 (KHTML, like Gecko) Chrome/68.0.3440.84 Safari/537.36");
                    MyWebClient.Credentials = CredentialCache.DefaultCredentials;
                    Byte[] pageData = MyWebClient.DownloadData(url);
                    pageHtml = encode.GetString(pageData);
                }
            }
            catch { }
            return pageHtml;
        }

        static void Main(string[] args)
        {
            var html = HttpGetPage("https://www.baidu.com","utf-8");

            Console.WriteLine(html);
            Console.ReadKey();
        }
    }
}

POST请求与Get类似,此处封装一个HttpPost(url, dic);函数,传入网站路径以及需要推送的键值对,即可使用。

代码语言:javascript
复制
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Text;
using System.IO;

namespace ConsoleApplication1
{
    class Program
    {

        public static string HttpPost(string url, Dictionary<string, string> dic)
        {
            string result = "";
            HttpWebRequest req = (HttpWebRequest)WebRequest.Create(url);
            req.Method = "POST";
            req.UserAgent = "Mozilla/5.0 (Windows NT 10.0; WOW64)AppleWebKit/537.36";
            req.ContentType = "application/x-www-form-urlencoded";
            #region
            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;
        }

        static void Main(string[] args)
        {
            string url = "http://www.baidu.com/";
            Dictionary<string, string> dic = new Dictionary<string, string> { };
            dic.Add("username","lyshark");
            HttpPost(url, dic);

            Console.ReadKey();
        }
    }
}
本文参与 腾讯云自媒体同步曝光计划,分享自作者个人站点/博客。
原始发表:2021-12-11,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体同步曝光计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档