http://www.cnblogs.com/shanyou/archive/2012/03/21/2410739.html
http://msdn.microsoft.com/zh-cn/library/system.net.http.httpclient.aspx
http://code.msdn.microsoft.com/Introduction-to-HttpClient-4a2d9cee
using System.Net.Http; public static string GetHttpResponse(string queryUrl) { try { HttpClientHandler handler = new HttpClientHandler(); handler.UseDefaultCredentials = true; handler.CookieContainer = new CookieContainer(); handler.UseCookies = true; handler.AllowAutoRedirect = true; using (HttpClient client = new HttpClient(handler)) { // Add a user-agent header client.DefaultRequestHeaders.Add("user-agent", USERAGENT); Console.WriteLine("update user agent {0}", client.DefaultRequestHeaders.UserAgent); // add referer client.DefaultRequestHeaders.Add("referer", REFERER); Console.WriteLine("update referer {0}", client.DefaultRequestHeaders.Referrer); //add accept client.DefaultRequestHeaders.Add("accept", ACCEPT); Console.WriteLine("update accept {0}", client.DefaultRequestHeaders.Accept); // add accept-encoding client.DefaultRequestHeaders.Add("accept-encoding", ACCEPTENCODING); Console.WriteLine("update encoding {0}", client.DefaultRequestHeaders.AcceptEncoding); // compose the url string requestUrl = string.Format("{0}{1}", BINGDEXURL, queryUrl); // send request var result = client.GetAsync(requestUrl).Result; string res = result.Content.ReadAsStringAsync().Result; Console.WriteLine("res \n" + res); File.WriteAllText(@"D:\temp2.html", res); return res; } } catch (Exception ex) { Console.WriteLine(string.Format("Failed while getting response for {0} with below error message", queryUrl)); Console.WriteLine(ex.Message); } return null; }
C#: Create a WebRequest with HTTPClient
时间: 2024-10-03 21:54:14