(43)C#网络1 http

一、HttpClient类

用于发送http请求,并接受请求的相应

(从4.5起开始可用)

using System.Net.Http;

  异步调用

            HttpClient httpClient = new HttpClient();
            //获取或设置读取响应内容时要缓冲的最大字节数,要在发送请求前设置
            httpClient.MaxResponseContentBufferSize = 100000;
            //获取或设置请求超时前等待的时间跨度
            httpClient.Timeout = TimeSpan.FromSeconds(1);
            //以异步操作将 GET 请求发送给指定 URI,返回一个HttpResponseHeaders对象
            HttpResponseMessage httpResponse = await httpClient.GetAsync("https://www.baidu.com/");
            Console.WriteLine(httpResponse.Content.ReadAsStringAsync().Result);

 

添加请求头

            HttpClient httpClient = new HttpClient();
            httpClient.DefaultRequestHeaders.Add("Accept","application/json;odata=verbose");

 

不用证书调用HTTPS

允许使用 HttpClient 颁发不受信任的 SSL 证书

using System.Net.Security;
using System.Security.Cryptography.X509Certificates;

var handler = new HttpClientHandler();

handler.ServerCertificateCustomValidationCallback =
(
  HttpRequestMessage message,
  X509Certificate2 cert,
  X509Chain chain,
  SslPolicyErrors errors
 ) =>
{ return true; };

using (var client = new HttpClient(handler))
{
    var response = await client.PostAsync("https://192.168.1.1:7999/CarList", null);
    string result = response.Content.ReadAsStringAsync().Result;
    Console.WriteLine(result);
}

 

调用https加头信息和body信息

var handler = new HttpClientHandler();

handler.ServerCertificateCustomValidationCallback =
(
  HttpRequestMessage message,
  X509Certificate2 cert,
  X509Chain chain,
  SslPolicyErrors errors
 ) =>
{ return true; };

using (var client = new HttpClient(handler))
{

    //var response = await client.PostAsync("https://192.165.2.88:7000/FpesMeter/CarList", null);

    client.DefaultRequestHeaders.Add("akey", "5e123d9edc");
    string requestBody = "{\"p21d\":\"57c9136\"}";
    var response = await client.PostAsync("https://192.168.1.24:8000/s1/23/token", new StringContent(requestBody, Encoding.UTF8, "application/json"));

    string result = response.Content.ReadAsStringAsync().Result;

    Console.WriteLine(result);

}

 

 

二、HttpResponseMessage 类

用于接收 http请求返回的数据和状态码

 

        static void Main(string[] args)
        {
            GetData();
            Console.ReadKey();
        }
        private static async void GetData()
        {
            HttpClient httpClient = new HttpClient();
            HttpResponseMessage httpResponse = null;
            httpResponse = await httpClient.GetAsync("http://www.baidu.com/");
            if (httpResponse.IsSuccessStatusCode)
            {
                //获取或设置 HTTP 响应的状态,
                Console.WriteLine("HTTP 响应的状态代码: " + httpResponse.StatusCode);
                //获取或设置通常由服务器发出的原因短语(与状态代码一起发出)
                Console.WriteLine("服务器发出的原因短语: " + httpResponse.ReasonPhrase);
                //获取 HTTP 响应标头的集合
                Console.WriteLine("HTTP 响应标头信息:" + httpResponse.Headers);
                //获取或设置 HTTP 响应消息的内容******
                Console.WriteLine("HTTP 响应消息的内容: " + httpResponse.Content.ReadAsStringAsync().Result);
                //获取或设置 HTTP 消息版本
                Console.WriteLine("HTTP 消息版本: " + httpResponse.Version);
            }
        }
    }

 

三、HttpRequestMessage类

表示一条 HTTP 请求消息

            HttpClient httpClient = new HttpClient();
            HttpRequestMessage httpRequestMessage = new HttpRequestMessage();
            //获取或设置用于 HTTP 请求的 Uri
            httpRequestMessage.RequestUri= new Uri("https://www.baidu.com");
            var task = httpClient.SendAsync(httpRequestMessage);
            task.Result.EnsureSuccessStatusCode();
            HttpResponseMessage response = task.Result;
            Console.WriteLine(response.Content.ReadAsStringAsync().Result);

 

 

HttpRequestHeaders 类

请求标头

 

 

四、HttpContent 类

表示 HTTP 实体正文和内容标头的基类

 

 

五、HttpMessageHandler 类

HTTP 消息处理程序的基类

HttpClient 类可以把HttpMessageHandler作为其构造函数的参数来定制请求

 

六、把输出结果显示为html

 

 

七、代理WebProxy

            //代理服务器的ip和端口号
            WebProxy proxy = new WebProxy("45.77.xxx.xxx", 8888);
            //用户名密码
            proxy.Credentials = new NetworkCredential("root","mengmeng");
            var handler = new HttpClientHandler { Proxy = proxy };
            var client = new HttpClient(handler);
            //要访问的目的网址
            HttpResponseMessage response = await client.GetAsync("https://www.youtuxx.com/?hl=zh-CN");
            Console.WriteLine(await response.Content.ReadAsStringAsync());

 

 

httpwebrequest

using System;
using System.Net;
using System.Security.Cryptography.X509Certificates;

class Program
{
    static void Main(string[] args)
    {
        // 创建 HttpWebRequest 对象
        HttpWebRequest request = (HttpWebRequest)WebRequest.Create("https://example.com");

        // 忽略服务器的 SSL 证书信任
        request.ServerCertificateValidationCallback = (sender, cert, chain, sslPolicyErrors) =>
        {
            // 始终返回 true,表示信任证书
            return true;
        };

        // 发送请求
        HttpWebResponse response = (HttpWebResponse)request.GetResponse();

        // 处理响应
        if (response.StatusCode == HttpStatusCode.OK)
        {
            // ...
        }
    }
}

 

posted @ 2018-03-05 11:10  富坚老贼  阅读(231)  评论(0编辑  收藏  举报