C#: Create a WebRequest with HTTPClient
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; }
郑重声明:本站内容如果来自互联网及其他传播媒体,其版权均属原媒体及文章作者所有。转载目的在于传递更多信息及用于网络分享,并不代表本站赞同其观点和对其真实性负责,也不构成任何其他建议。