C# - 从WebRequest获取响应并处理状态代码

时间:2021-01-08 00:13:38

I am writing an updatesystem for .NET-applications and at the moment I am stuck. I try to get a file on a remote server and its content. For that I want to use a HttpWebRequest to get the content and the status code if the operation fails.

我正在为.NET应用程序编写一个更新系统,目前我陷入困境。我尝试在远程服务器上获取文件及其内容。为此,如果操作失败,我想使用HttpWebRequest来获取内容和状态代码。

I built a function that contains a switch-query and each part asks the status code and does an action then.

我构建了一个包含switch-query的函数,每个部分都会询问状态代码并执行操作。

This looks like the following:

这看起来如下:

public void AskStatusCode(int code)
{
  switch (code)
  {
  case 404:
     // Do an action
     break;

  case 405:
     // Do an action
     break;
  }
}

Ok, that is it. Now I created a HttpWebRequest and a HttpWebResponse.

好的,就是这样。现在我创建了一个HttpWebRequest和一个HttpWebResponse。

HttpWebRequest requestChangelog = (HttpWebRequest)HttpWebRequest.Create(url);
requestChangelog.Method = "GET";

HttpWebResponse changelogResponse = (HttpWebResponse)requestChangelog.GetResponse();

// Now call the function and set the status code of the response as parameter.
AskStatusCode((int)changelogResponse.StatusCode);

So, the theory should work, but it does not. It will not do any actions I put in the "case"-block for a special status code.

因此,理论应该有效,但事实并非如此。它不会对特殊状态代码的“case”-block进行任何操作。

I removed the file from the remote server to test if it will execute the case-block for code "404", but it always shows me an exception (remote server answered 404), but not that what I wanted this status code to handle with.

我从远程服务器上删除了该文件以测试它是否会执行代码“404”的case-block,但它总是向我显示异常(远程服务器回答404),但不是我希望这个状态代码要处理的。

So, my question is, why is this not working? The types are integers and I casted the status code to an Int32 as well, as you could see...

所以,我的问题是,为什么这不起作用?类型是整数,我也将状态代码转换为Int32,你可以看到......

To your info: After the status code had been checked and if it is ok, I want to read the content with a stream reader and the ResponseStream.

您的信息:检查状态代码后,如果没问题,我想用流阅读器和ResponseStream阅读内容。

Help would be appreciated. Excuse me, if you did not understand that, I tried to say it as clear as I could.

帮助将不胜感激。对不起,如果你不明白,我试着尽可能地说清楚。

2 个解决方案

#1


17  

You have to check whether the response failed because of a server error (the WebException provides a WebResponse) or not. Maybe this will help you:

您必须检查响应是否因服务器错误(WebException提供WebResponse)而失败。也许这会对你有所帮助:

        HttpWebResponse response = null;

        try
        {
            HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create("http://www.google.com/thisisadeadlink");
            request.Method = "GET";

            response = (HttpWebResponse)request.GetResponse();

            StreamReader sr = new StreamReader(response.GetResponseStream());
            Console.Write(sr.ReadToEnd());
        }
        catch (WebException e)
        {
            if (e.Status == WebExceptionStatus.ProtocolError)
            {
                response = (HttpWebResponse)e.Response;
                Console.Write("Errorcode: {0}", (int)response.StatusCode);
            }
            else
            {
                Console.Write("Error: {0}", e.Status);
            }
        }
        finally
        {
            if (response != null)
            {
                response.Close();
            }
        }

#2


5  

StatusCodes in the range of 4xx and 5xx throw a WebException which is why the code is never reaching the switch statement.

4xx和5xx范围内的StatusCodes抛出WebException,这就是代码永远不会到达switch语句的原因。

You need to handle this exception in your code:

您需要在代码中处理此异常:

HttpWebRequest requestChangelog = null;
HttpWebResponse changelogResponse = null;

try
{
    requestChangelog = (HttpWebRequest)HttpWebRequest.Create(url);
    requestChangelog.Method = "GET";

    changelogResponse = (HttpWebResponse)requestChangelog.GetResponse();
}
catch (WebException we)
{
    //handle the error
}

AskStatusCode((int)changelogResponse.StatusCode);

If you are only interested in checking error status codes then you would move the AskStatusCode() call inside of the catch block.

如果您只对检查错误状态代码感兴趣,那么您将在catch块内移动AskStatusCode()调用。

#1


17  

You have to check whether the response failed because of a server error (the WebException provides a WebResponse) or not. Maybe this will help you:

您必须检查响应是否因服务器错误(WebException提供WebResponse)而失败。也许这会对你有所帮助:

        HttpWebResponse response = null;

        try
        {
            HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create("http://www.google.com/thisisadeadlink");
            request.Method = "GET";

            response = (HttpWebResponse)request.GetResponse();

            StreamReader sr = new StreamReader(response.GetResponseStream());
            Console.Write(sr.ReadToEnd());
        }
        catch (WebException e)
        {
            if (e.Status == WebExceptionStatus.ProtocolError)
            {
                response = (HttpWebResponse)e.Response;
                Console.Write("Errorcode: {0}", (int)response.StatusCode);
            }
            else
            {
                Console.Write("Error: {0}", e.Status);
            }
        }
        finally
        {
            if (response != null)
            {
                response.Close();
            }
        }

#2


5  

StatusCodes in the range of 4xx and 5xx throw a WebException which is why the code is never reaching the switch statement.

4xx和5xx范围内的StatusCodes抛出WebException,这就是代码永远不会到达switch语句的原因。

You need to handle this exception in your code:

您需要在代码中处理此异常:

HttpWebRequest requestChangelog = null;
HttpWebResponse changelogResponse = null;

try
{
    requestChangelog = (HttpWebRequest)HttpWebRequest.Create(url);
    requestChangelog.Method = "GET";

    changelogResponse = (HttpWebResponse)requestChangelog.GetResponse();
}
catch (WebException we)
{
    //handle the error
}

AskStatusCode((int)changelogResponse.StatusCode);

If you are only interested in checking error status codes then you would move the AskStatusCode() call inside of the catch block.

如果您只对检查错误状态代码感兴趣,那么您将在catch块内移动AskStatusCode()调用。