一、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");
二、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());