我有以下方法,它返回给定Url
的Http status code
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
,并且它应该有一个包含重定向指向的头部。
我在其他的.Net web请求类中也看到过类似的东西,以及将某种allowAutoRedirect
属性设置为false的技术。如果这是正确的,谁能告诉我HttpClient
类的正确替代方案?
This post has info on the above allowAutoRedirect concept I mean
否则,对于我知道是真正的301s
的Urls,我如何让此方法返回301s
而不是200s
发布于 2013-02-06 23:16:25
我发现实现此目的的方法是创建一个HttpClientHandler
实例并将其传递到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))
{
}
有关详细信息,请参阅here。
https://stackoverflow.com/questions/14731980
复制相似问题