C# WebClient,HttpClient,WebRequest
static void WebClientDemo() { string url = "https://www.cnblogs.com/Fred1987/p/11843418.html"; WebClient wc = new WebClient(); string content=wc.DownloadString(url); Console.WriteLine(content); } static async void HttpClientDemo() { try { string url = "https://www.cnblogs.com/Fred1987/p/11843418.html"; using (HttpClient httpClient = new HttpClient()) { HttpResponseMessage httpResponse = await httpClient.GetAsync(url); httpResponse.EnsureSuccessStatusCode(); string responseBody = await httpResponse.Content.ReadAsStringAsync(); Console.WriteLine(responseBody); } } catch(HttpRequestException ex) { Console.WriteLine(ex.Message); } } static void WebRequestDemo() { string url = "https://www.cnblogs.com/Fred1987/p/11843418.html"; WebRequest webRequest = WebRequest.Create(url); using (WebResponse webResponse = webRequest.GetResponse()) { Stream responseStream = webResponse.GetResponseStream(); StreamReader streamReader = new StreamReader(responseStream); string result = streamReader.ReadToEnd(); Console.WriteLine(result); } }
static void Main(string[] args) { WebRequestAsyncDemo(); Console.ReadLine(); } static void WebRequestAsyncDemo() { string url = "https://docs.microsoft.com/en-us/dotnet/api/system.string?f1url=https%3A%2F%2Fmsdn.microsoft.com%2Fquery%2Fdev16.query%3FappId%3DDev16IDEF1%26l%3DEN-US%26k%3Dk(System.String);k(TargetFrameworkMoniker-.NETFramework,Version%3Dv4.8);k(DevLang-csharp)%26rd%3Dtrue&view=netframework-4.8"; Task task = WriteWebRequestAsync(url); try { while(!task.Wait(100)) { Console.Write("."); } } catch(AggregateException aes) { aes = aes.Flatten(); try { aes.Handle(x => { Console.WriteLine(x.Message); return true; }); } catch(WebException) { } catch(IOException) { } catch(NotSupportedException) { } } } static Task WriteWebRequestAsync(string url) { StreamReader reader = null; WebRequest request = WebRequest.Create(url); Task task = request.GetResponseAsync().ContinueWith(x => { WebResponse response = x.Result; reader = new StreamReader(response.GetResponseStream()); return reader.ReadToEndAsync(); }).Unwrap().ContinueWith(x => { if (reader != null) { reader.Dispose(); } string text = x.Result; Console.WriteLine(text); }); return task; }
static void Main(string[] args)
{
WebRequestDemoAsync();
Console.ReadLine();
}
static async void WebRequestDemoAsync()
{
string url = "https://docs.microsoft.com/en-us/dotnet/api/system.string?f1url=https%3A%2F%2Fmsdn.microsoft.com%2Fquery%2Fdev16.query%3FappId%3DDev16IDEF1%26l%3DEN-US%26k%3Dk(System.String);k(TargetFrameworkMoniker-.NETFramework,Version%3Dv4.8);k(DevLang-csharp)%26rd%3Dtrue&view=netframework-4.8";
WebRequest request = WebRequest.Create(url);
WebResponse response =await request.GetResponseAsync();
using(StreamReader reader=new StreamReader(response.GetResponseStream()))
{
string text = await reader.ReadToEndAsync();
Console.WriteLine(text);
}
}