Gga*_*Gga 33 c# redirect http httpclient
我有以下方法返回Http status code给定的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);
}
Run Code Online (Sandbox Code Playgroud)
它适用于200/ 404etc,但是在301代码的情况下,我认为返回的结果是已经重定向的(200)结果,而不是301应该返回的实际结果,并且具有包含重定向将指向的位置的标头.
我在其他.Net Web请求类中看到了类似的东西,并且将某种allowAutoRedirect属性设置为false.如果这是沿着正确的路线,有人能告诉我正确的选择HttpClient吗?
这篇文章有关于上面的allowAutoRedirect概念的信息,我的意思是
另外,我怎么能让这种方法返回301s而不是200s我认为真实的网址301s呢?
Gga*_*Gga 56
我发现这样做的方法是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))
{
}
Run Code Online (Sandbox Code Playgroud)
有关详细信息,请参见此处
| 归档时间: |
|
| 查看次数: |
20563 次 |
| 最近记录: |