HttpWebRequest GetResponseAsync抛出异常

时间:2018-06-14 08:00:14

标签: c# exception httpwebrequest httpwebresponse

按照 C#6.0 Cookbook中的配方(配方9.2与Web服务器通信和配方9.1处理Web服务器错误),我创建了以下内容:

try
  {
      HttpWebRequest request = (HttpWebRequest)WebRequest.Create(new Uri(urlstring));

      if (request == null) return;

      request.ContentType = "application/json";
      request.Headers.Add("customHeader", "blablabla");

      request.ContentLength = bytes.Length;
      request.Method = "POST";

     // Get the request stream and write the post data in
     using (Stream requestStream = request.GetRequestStream())
       {
         requestStream.Write(bytes, 0, bytes.Length);
       // await requestStream.WriteAsync(bytes, 0, bytes.Length);
        }



     using (HttpWebResponse response = (HttpWebResponse)await request.GetResponseAsync())
        {
        ResponseCategories rr;
   //CategorizeResponse is recipe 9.1
        if ((rr = CategorizeResponse(response)) == ResponseCategories.Success)
           {
             Console.WriteLine("Request succeeded");
            }
         else
          {
           Console.WriteLine("The response was not success " + rr.ToString());
           }
        }
 }
 catch (Exception ex)
 {    
  Console.WriteLine("Something happened, oopps!" + ex.Message);   
 }

正如评论所说,CategorizeResponse是配方9.1中的一个功能,它基本上采用HttpWebResponse并根据其StatusCode将其分类为名为ResponseCategories的枚举类型。

所以我执行此操作并捕获异常。 using (HttpWebResponse response = (HttpWebResponse)await request.GetResponseAsync())

抛出异常

我得到的异常是远程服务器返回了错误(400)请求格式错误。

这还不错,因为请求确实格式不正确,远程服务器必须用400回复我(错误)。这是预料之中的。

我的问题来自于我原本期望这些"错误"由CategorizeResponse函数在使用中处理。

当服务器响应不成功时,GetResponseAsync总是会抛出异常吗?有没有办法从服务器识别错误消息而不抛出异常?

0 个答案:

没有答案