常见的Web页面获取页面内容用 WebRequest 或者 HttpWebRequest 来操作 Http 请求。
例如,获取百度网站的 html 页面
var request = WebRequest.Create("http://www.baidu.com"); request.Method = "GET"; var response = request.GetResponse(); using (var stream = new System.IO.StreamReader(response.GetResponseStream())) { var content = stream.ReadToEnd();//获取到远程的页面字符串 Console.WriteLine(content); }
POST 请求
var jsonToPost = "{"name":"admin","pwd":"123456"}"; var request = WebRequest.Create("http://www.sina.com"); request.Method = "POST"; using (var requestStream = request.GetRequestStream()) { var bytes = Encoding.UTF8.GetBytes(jsonToPost); requestStream.Write(bytes, 0, bytes.Length); } var response = request.GetResponse(); using (var stream = new System.IO.StreamReader(response.GetResponseStream())) { var content = stream.ReadToEnd();//获取 Post 返回的内容 }
还有一种方式请求,那就是HttpClient 这种方式,这种方式不常见,不过相比上面的的方式还是比较简洁的,一句代码就实现的肯定是好的方法嘛。
using (var http = new HttpClient()) { var content= http.GetAsync("http://www.baidu.com").GetAwaiter().GetResult() .Content.ReadAsStringAsync().GetAwaiter().GetResult(); }
POST请求
using (var http = new HttpClient()) { var jsonToPost = "{"name":"admin","pwd":"123456"}"; var content = http.PostAsync("http://www.baidu.com", new StringContent(jsonToPost)).GetAwaiter().GetResult() .Content.ReadAsStringAsync().GetAwaiter().GetResult(); }
如果还有更好的方式后续欢迎大家一起交流学习!