C#HttpClient.SendAsync抛出“发送请求时发生错误”;测试某些URL时出现异常 [英] C# HttpClient.SendAsync throw "An error occurred while sending the request" exception when testing some URLs

查看:1060
本文介绍了C#HttpClient.SendAsync抛出“发送请求时发生错误”;测试某些URL时出现异常的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在开发一个C#控制台应用程序,用于测试URL是否有效。它适用于大多数URL,并且可以从目标网站获得HTTP状态代码的响应。但是,当测试其他一些URL时,运行HttpClient.SendAsync方法时,应用程序将引发发送请求时发生错误异常。因此,即使该URL实际上在浏览器中也可以使用,我无法获得任何响应或HTTP状态代码。我很想知道如何处理这种情况。如果该网址无效或服务器拒绝了我的请求,则至少应给我相应的HTTP状态代码。

I am developing an C# console application for testing whether a URL is valid or works. It works well for most of URLs and can get response with HTTP Status Code from target website. But when testing some other URLs, the application throw an "An error occurred while sending the request" exception when running HttpClient.SendAsync method. So I can't get any response or HTTP Status Code even this URL actually works in the browser. I am desperate to find out how to handle this case. If the URL doesn't work or the server reject my request, it should at least give me corresponding HTTP Status code.

这是我的测试应用程序的简化代码:

Here are the simplified code of my test application:

using System;
using System.Net.Http;
using System.Threading.Tasks;

namespace TestUrl
{
    class Program
    {
        static void Main(string[] args)
        {
           // var urlTester = new UrlTester("http://www.sitename.com/wordpress"); // works well and get 404
           // var urlTester = new UrlTester("http://www.fc.edu/"); // Throw exception and the URL doesn't work
           var urlTester = new UrlTester("http://www.ntu.edu.tw/english/"); // Throw exception and the URL works actually

            Console.WriteLine("Test is started");

            Task.WhenAll(urlTester.RunTestAsync());

            Console.WriteLine("Test is stoped");
            Console.ReadKey();
        }


        public class UrlTester
        {
            private HttpClient _httpClient;
            private string _url;

            public UrlTester(string url)
            {
                _httpClient = new HttpClient();
                _url = url;
            }

            public async Task RunTestAsync()
            {
                var httpRequestMsg = new HttpRequestMessage(HttpMethod.Head, _url);

                try
                {
                    using (var response = await _httpClient.SendAsync(httpRequestMsg, HttpCompletionOption.ResponseHeadersRead))
                    {
                        Console.WriteLine("Response: {0}", response.StatusCode);
                    }
                }
                catch (Exception e) 
                { 
                }
            }
        }

    }
} 


推荐答案

如果您查看 InnerException 您将看到:


无法解析远程名称:'www。 fc.edu'

"The remote name could not be resolved: 'www.fc.edu'"

此URL也无法在我的浏览器上使用。

This URL does not work on my browser either.

为了获得HTTP响应,您需要客户端能够与服务器通信(甚至为了获得错误404 ),并且在您的情况下,发生了在DNS级别

In order to get an HTTP response you need the client to be able to communicate with the server (even in order to get error 404) and in your case the error occurred at the DNS level.

某些浏览器会在这种情况下自动完成,如果未找到特定的URL,则浏览器将使用不同的s重试。后缀/前缀,例如:

Some browsers have auto-completion for this kind of cases where if a specific URL is not found, the browser retries with a different suffix/prefix, for example:

try "x"
if didn't work, try "www." + x
if this didn't work try "www." + x + ".com"
if this didn't work try "www." + x + ".net"
if this didn't work try "www." + x + "." + currentRegionSuffix.

但是请注意,您可以从以下代码中更改代码:

But note that you can change your code from:

catch (Exception e)
{

}

收件人:

catch (HttpRequestException e)
{
    Console.WriteLine(e.InnerException.Message);
}

您将能够看到导致错误的原因。

And you will be able to see what causes your error.

此外, 除非抛出者抛出了普通的<$,否则您永远都不想捕获普通的 Exception c $ c> Exception ,甚至永远不要捕获异常,也不做任何事情,至少要记录下来。

Also, You should never want to catch the generic Exception unless the thrower has thrown the generic Exception, and even than, never catch and do nothing with the exception, at least log it.

注意,由于您只等待一个任务,因此可以使用:

Notice than since you wait only for that one task you can use:

urlTester.RunTestAsync().Wait();

而不是:

Task.WhenAll(urlTester.RunTestAsync());

Task.WhenAll 创建一个新的任务完成给定的任务后。在您的情况下,您需要 Task.WaitAll Task。 WhenAll(...)。Wait()

Task.WhenAll creates a new Task when the given Tasks are completed. in your case you need Task.WaitAll or Task.WhenAll(...).Wait().

这篇关于C#HttpClient.SendAsync抛出“发送请求时发生错误”;测试某些URL时出现异常的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆