常见的Web页面获取页面内容用 WebRequest 或者 HttpWebRequest 来操纵 Http 请求。
例如,获取百度网站的 html 页面
var request = WebRequest.Create(""); 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(""); 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("").GetAwaiter().GetResult() .Content.ReadAsStringAsync().GetAwaiter().GetResult(); }
POST请求
using (var http = new HttpClient()) { var jsonToPost = "{\"name\":\"admin\",\"pwd\":\"123456\"}"; var content = http.PostAsync("", new StringContent(jsonToPost)).GetAwaiter().GetResult() .Content.ReadAsStringAsync().GetAwaiter().GetResult(); }
如果还有更好的方法后续欢迎大家一起交流学习!