zoukankan      html  css  js  c++  java
  • .Net(c#)模拟Http请求之HttpWebRequest封装

    一、需求:

      向某个服务发起请求获取数据,如:爬虫,采集。

    二、步骤(HttpWebRequest):

    无非在客户端Client(即程序)设置请求报文(如:Method,Content-Type,Agent,Cookie以及请求参数等信息)向服务端Server发送请求,服务端响应数据。

    三、源码简介:

    ①.HttpUtil类:HttpWebRequest封装的核心

    ②.HttpRequestParameter类:请求报文类

    ③.HttpResponseParameter类:响应报文类

    ④.HttpCookieType类:请求/响应需要的Cookie封装

    四、运行测试:

    class Program
    {
        static void Main(string[] args)
        {
            IHttpProvider httpProvider = new HttpProvider();
    
            // 1. 模拟一个Get请求方式
            HttpResponseParameter responseParameter1 = httpProvider.Excute(new HttpRequestParameter
            {
                Url = "http://www.baidu.com",
                IsPost = false,
                Encoding = Encoding.UTF8
                //Cookie = new HttpCookieType() 如果需要Cookie
            });
            System.Console.WriteLine(responseParameter1.Body);
    
            // 2. 模拟一个Post请求方式(例:登录)
            IDictionary<string, string> postData = new Dictionary<string, string>();
            postData.Add("userName", "登录用户名");
            postData.Add("userPwd", "用户名密码");
            HttpResponseParameter responseParameter2 = httpProvider.Excute(new HttpRequestParameter
            {
                Url = "你的登录url",
                IsPost = true,
                Encoding = Encoding.UTF8,
                Parameters = postData
            });
            System.Console.WriteLine(responseParameter2.Body);
    
            System.Console.ReadLine();
        }
    }

    尽情地为所欲为吧……

    五、源码下载:点我

  • 相关阅读:
    Nginx+Keepalived(双机热备)搭建高可用负载均衡环境(HA)
    库管理系统-- 后台管理开源啦,源码大放送
    .NET Core R2
    Linux gdb调试
    webpack React+ES6
    绿卡排队
    ABP分层设计
    vscode编写插件
    控制台程序的参数解析类库 CommandLine
    Net Core MVC6 RC2 启动过程分析
  • 原文地址:https://www.cnblogs.com/GodX/p/4226788.html
Copyright © 2011-2022 走看看