HttpClient的请求像浏览器 [英] HttpClient Request like browser
问题描述
当我打电话网站www.livescore.com通过的HttpClient类,我总是得到错误500。
从HttpClients可能阻塞服务器的请求。
When I calling site www.livescore.com by HttpClient class I always getting error "500". Probably server blocked request from HttpClients.
1)有其他任何方法从网页上获取的HTML?
1)There is any other method to get html from webpage?
2)如何设置标题来获得HTML内容?
2)How I can set the headers to get html content?
当我设置头就像在浏览器中我总是STANGE EN codeD的内容。
When I set headers like in browser I always get stange encoded content.
http_client.DefaultRequestHeaders.TryAddWithoutValidation("Accept", "text/html,application/xhtml+xml,application/xml");
http_client.DefaultRequestHeaders.TryAddWithoutValidation("Accept-Encoding", "gzip, deflate");
http_client.DefaultRequestHeaders.TryAddWithoutValidation("User-Agent", "Mozilla/5.0 (Windows NT 6.2; WOW64; rv:19.0) Gecko/20100101 Firefox/19.0");
http_client.DefaultRequestHeaders.TryAddWithoutValidation("Accept-Charset", "ISO-8859-1");
3)如何我可以解决售后服务这个问题?有什么建议?
3) How I can slove this problem? Any suggestions?
我在C#中使用Windows 8 Metro风格应用和HttpClientClass
I using Windows 8 Metro Style App in C# and HttpClientClass
推荐答案
在这里你去 - 注意,您必须DECOM preSS gzip的EN codeD-结果你回来的as每 mleroy :
Here you go - note you have to decompress the gzip encoded-result you get back as per mleroy:
private static async Task<string> GetResponse(string url)
{
var httpClient = new HttpClient();
httpClient.DefaultRequestHeaders.TryAddWithoutValidation("Accept", "text/html,application/xhtml+xml,application/xml");
httpClient.DefaultRequestHeaders.TryAddWithoutValidation("Accept-Encoding", "gzip, deflate");
httpClient.DefaultRequestHeaders.TryAddWithoutValidation("User-Agent", "Mozilla/5.0 (Windows NT 6.2; WOW64; rv:19.0) Gecko/20100101 Firefox/19.0");
httpClient.DefaultRequestHeaders.TryAddWithoutValidation("Accept-Charset", "ISO-8859-1");
var response = await httpClient.GetAsync(new Uri(url));
response.EnsureSuccessStatusCode();
using (var responseStream = await response.Content.ReadAsStreamAsync())
using (var decompressedStream = new GZipStream(responseStream, CompressionMode.Decompress))
using (var streamReader = new StreamReader(decompressedStream))
{
return streamReader.ReadToEnd();
}
}
通话等类:
var response = await GetResponse("http://www.livescore.com/"); // or var response = GetResponse("http://www.livescore.com/").Result;
这篇关于HttpClient的请求像浏览器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!