首页 > 代码库 > C#: Create a WebRequest with HTTPClient
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; }
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。