使用HttpClient的,我将如何阻止自动重定向并获得原有的状态代码和301的情况下forwading网址 [英] Using HttpClient, how would I prevent automatic redirects and get original status code and forwading Url in the case of 301
问题描述
我有以下的方法,返回给定网址
的 HTTP状态代码
:
I have the following method that returns the Http status code
of a given Url
:
public static async void makeRequest(int row, string url)
{
string result;
Stopwatch sw = new Stopwatch(); sw.Start();
try
{
using (HttpClient client = new HttpClient())
{
HttpResponseMessage response = new HttpResponseMessage();
response = await client.GetAsync(url);
// dump contents of header
Console.WriteLine( response.Headers.ToString() );
if (response.IsSuccessStatusCode)
{
result = ((int)response.StatusCode).ToString();
}
else
{
result = ((int)response.StatusCode).ToString();
}
}
}
catch (HttpRequestException hre)
{
result = "Server unreachable";
}
sw.Stop();
long time = sw.ElapsedTicks / (Stopwatch.Frequency / (1000L * 1000L));
requestComplete(row, url, result, time);
}
它非常适用 200
/ 404
等,但是在 301
码的情况下,我相信返回的结果是的已重定向的的( 200
)的结果,而不是实际的 301
应该返回而这将对包含其中重定向会指着头。
It works well for 200
/404
etc, however in the case of 301
codes I believe the returned result is the already-redirected (200
) result, rather than the actual 301
that should be returned and which would have a header containing where the redirect would be pointed to.
我见过这样的事情在其他.NET Web请求的类和技术有设置某种 allowAutoRedirect
属性设置为false的。如果这是沿着正确的方向,谁能告诉我的的HttpClient
类的正确选择吗?
I have seen something like this in other .Net web requests classes and the technique there was to set some sort of allowAutoRedirect
property to false. If this is along the right lines, can anyone tell me the correct alternative for the HttpClient
class?
<一个HREF =http://stackoverflow.com/questions/690587/using-webclient-in-c-sharp-is-there-a-way-to-get-the-url-of-a-site-after-being -r>这个职位对上述allowAutoRedirect概念信息我的意思是
否则,我怎么可能会得到这个方法返回 301S
,而不是 200S
对于网址我知道是真实的 301S
?
Else, how might I get this method to return 301s
rather than 200s
for Urls I know to be genuine 301s
?
推荐答案
我发现,这样做,这是通过创建 HttpClientHandler
的一个实例并通过它的HttpClient
I have found that the way to do this is by creating an instance of HttpClientHandler
and passing it in the constructor of HttpClient
public static async void makeRequest(int row, string url)
{
string result;
Stopwatch sw = new Stopwatch(); sw.Start();
// added here
HttpClientHandler httpClientHandler = new HttpClientHandler();
httpClientHandler.AllowAutoRedirect = false;
try
{
// passed in here
using (HttpClient client = new HttpClient(httpClientHandler))
{
请参阅的这里获取更多信息。
See here for more info.
这篇关于使用HttpClient的,我将如何阻止自动重定向并获得原有的状态代码和301的情况下forwading网址的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!