C#HttpWebResponse,WebException

时间:2015-04-24 07:20:24

标签: c# json httpwebrequest httpwebresponse system.net.webexception

所以,我对C#很新,但我使用过其他语言。 目前我正在编写一个定制的MineCraft发射器。 我正在使用Yggdrasil Authentication Documentation来帮助我这样做。 它说: 如果请求成功,服务器将响应:

  • 状态代码200
  • 根据以下规范的JSON编码字典

如果请求失败,服务器将回复:

  • 适当的非200 HTTP状态代码
  • 遵循以下格式的JSON编码字典:

我已经解决了第一部分,但第二部分是问题所在!

HttpWebResponse httpResponse = null;
try
{
    httpResponse = (HttpWebResponse)httpWebRequest.GetResponse();
    using (StreamReader streamReader = new StreamReader(httpResponse.GetResponseStream()))
    {
        string result = streamReader.ReadToEnd();
        Console.WriteLine(result);
    }
}
catch (WebException e)
{
    Console.WriteLine(e.ToString());
}

如您所见,如果发生WebException,例如我收到403 Forbidden错误,我就无法读取内容。我得到一个NullReferenceException。

所以,问题是:如果HttpWebRequest失败,如何获取WebResponse?

3 个答案:

答案 0 :(得分:0)

请检查以下方法以获取状态代码。

     HttpWebResponse httpResponse = null;
    try
    {
        httpResponse = (HttpWebResponse)httpWebRequest.GetResponse();
        using (StreamReader streamReader = new StreamReader(httpResponse.GetResponseStream()))
        {
            string result = streamReader.ReadToEnd();
            Console.WriteLine(result);
        }
    }
catch (WebException ex)
{
    if (ex.Status == WebExceptionStatus.ProtocolError)
    {
        var response = ex.Response as HttpWebResponse;
        if (response != null)
        {
            Console.WriteLine("HTTP Status Code: " + (int)response.StatusCode);
        }
        else
        {
            // no http status code available
        }
    }
    else
    {
        // no http status code available
    }
}

答案 1 :(得分:0)

您仍然可以使用WebException.Response属性

来阅读回复内容
HttpWebResponse httpResponse = null;
try
{
    httpResponse = (HttpWebResponse)httpWebRequest.GetResponse();
    using (StreamReader streamReader = new StreamReader(httpResponse.GetResponseStream()))
    {
        string result = streamReader.ReadToEnd();
        Console.WriteLine(result);
    }
}
catch (WebException e)
{
   Console.WriteLine(e.ToString());

   string responseText;
   using (var reader = new StreamReader(webException.Response.GetResponseStream()))
   {
       responseText = reader.ReadToEnd();
   }

   Console.WriteLine("WebException caught. Response text is {0}", responseText);
}

答案 2 :(得分:0)

你可以尝试这样的事情:

        var response = e.Response as HttpWebResponse;
         if (response!=null && response.StatusCode != HttpStatusCode.OK)
        {
            Console.WriteLine("HTTP Error Code is: " + (int)response.StatusCode);
        }