42

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);
}

200/404などではうまく機能しますが、301コードの場合、返される結果は、返されるはずの実際の結果ではなく、すでにリダイレクトされた( )結果であり、リダイレクトがポイントされる場所を含むヘッダーが含まれていると思います。200301

他の.NetWebリクエストクラスでこのようなものを見たことがあり、ある種のallowAutoRedirectプロパティをfalseに設定する手法がありました。HttpClientこれが正しい方向に進んでいる場合、誰かがクラスの正しい代替案を教えてもらえますか?

この投稿には、上記のallowAutoRedirectの概念に関する情報があります。

それ以外の場合、本物であることがわかっているURL301sではなく、このメソッドを返すにはどうすればよいですか?200s301s

4

1 に答える 1

75

これを行う方法は、のインスタンスを作成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))
        {

        }

詳細については、こちらをご覧ください。

于 2013-02-06T15:16:24.890 に答える