Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C# HttpClient.SendAsync throw "An error occurred while sending the request" exception when testing some URLs

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)                  {                  }             }         }      } }  
like image 558
codigube Avatar asked Oct 04 '15 09:10

codigube


People also ask

What is the full name of C?

In the real sense it has no meaning or full form. It was developed by Dennis Ritchie and Ken Thompson at AT&T bell Lab. First, they used to call it as B language then later they made some improvement into it and renamed it as C and its superscript as C++ which was invented by Dr.

What do you mean by C?

C is a structured, procedural programming language that has been widely used both for operating systems and applications and that has had a wide following in the academic community. Many versions of UNIX-based operating systems are written in C.

Is C language easy?

C is a general-purpose language that most programmers learn before moving on to more complex languages. From Unix and Windows to Tic Tac Toe and Photoshop, several of the most commonly used applications today have been built on C. It is easy to learn because: A simple syntax with only 32 keywords.

What is C language used for?

C programming language is a machine-independent programming language that is mainly used to create many types of applications and operating systems such as Windows, and other complicated programs such as the Oracle database, Git, Python interpreter, and games and is considered a programming foundation in the process of ...


1 Answers

If you look at the InnerException you will see that:

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

This URL does not work on my browser either.

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.

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

To:

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

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

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

Instead of:

Task.WhenAll(urlTester.RunTestAsync()); 

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

like image 50
Tamir Vered Avatar answered Sep 21 '22 06:09

Tamir Vered