8-网络请求之http

本篇博客对应视频讲解html

回顾

上一篇讲了Linq的使用,你们本身上手实践以后,相信必定会感到很是快捷方便。更多详细的内容仍是须要本身去阅读官方文档。 今天要讲网络请求中的http请求,这也是在编程当中常常使用到的内容之一。web

Http请求

关于Http是什么,请求类型这些内容我在此都不说了,须要你们本身阅读相关资料。一般来说,咱们在进行数据采集,API调用,模拟登陆等功能开发的时候,免不了使用http请求。 即便用浏览器能作到的事情,咱们均可以经过编程去实现。毕竟浏览器自己也是一种应用程序,也是编程的产出结果。 关于.Net 平台提供的网络编程相关内容,你们能够阅读官方文档编程

经常使用的类

进行网络请求,对于通常的需求,咱们使用HttpClientWebClient类便可。WebClient进行了更高级的封装,更容易使用,同时也意味着更少的自定义,更低的灵活性。 一般咱们进行网络请求要进行相关的步骤:浏览器

  1. 分析目标源,好比编码格式,返回内容,是否须要鉴权,访问限制等。
  2. 发送请求获取返回数据。
  3. 处理返回的数据。

咱们经过实际的例子来讲明:网络

  1. 将百度首页保存成baidu.html
            // webclient 的简单使用
            using (var wc = new WebClient())
            {
                // 设置编码
                wc.Encoding = Encoding.UTF8;
                // 请求内容
                var result = wc.DownloadString("https://www.baidu.com");
                // 保存到文件
                File.WriteAllText("baidu.html", result);
            }
  1. 使用httpClient进行多种方式请求 首先要知道请求能够有多种方式,能够传递参数、文件等内容。不一样的类型要构造不一样的请求内容的结构体。 C#提供了多种类型(继承HttpConent类)做为请求内容的容器。
// httpClient 请求
    using (var hc = new HttpClient())
    {
        string result = "";
        var httpResponse = new HttpResponseMessage();

        // get请求
        httpResponse = hc.GetAsync("https://www.baidu.com").Result;
        result = httpResponse.Content.ReadAsStringAsync().Result;
        Console.WriteLine(result);

        // post请求,构造不一样类型的请求内容
        var data = new List<KeyValuePair<string, string>> {
            new KeyValuePair<string, string>("from","msdev.cc"),
        };
        // 封闭成请求结构体
        var content = new FormUrlEncodedContent(data);
        // 进行请求,获取返回数据
        httpResponse = hc.PostAsync("https://msdev.cc", content).Result;
        // 将返回数据做为字符串
        result = httpResponse.Content.ReadAsStringAsync().Result;

        File.WriteAllText("post.html", result);
    }

    // 自定义请求及结果处理
    using (var hc = new HttpClient())
    {
        string result = "";
        var httpRequest = new HttpRequestMessage();
        var httpResponse = new HttpResponseMessage();
        // 请求方法
        httpRequest.Method = HttpMethod.Put;
        // 请求地址
        httpRequest.RequestUri = new Uri("https://msdev.cc");
        // 请求内容
        httpRequest.Content = new StringContent("request content");
        // 设置请求头内容
        httpRequest.Headers.TryAddWithoutValidation("", "");
        // 设置超时
        hc.Timeout = TimeSpan.FromSeconds(5);
        // 获取请求结果 
        httpResponse = hc.SendAsync(httpRequest).Result;
        // 判断请求结果
        if (httpResponse.StatusCode == HttpStatusCode.OK)
        {
            result = httpResponse.Content.ReadAsStringAsync().Result;
            File.WriteAllText("custom.html", result);
        }
        else
        {
            Console.WriteLine(httpResponse.StatusCode + httpResponse.RequestMessage.ToString());
        }
    }
相关文章
相关标签/搜索