简体   繁体   English

HttpWebRequest正确的异常处理

[英]HttpWebRequest proper exception handling

So I'm using the HttpWebRequest API in the System.Net assembly but because C# has no checked exceptions, I'm not sure where to put my try-catch blocks to properly handle inevitable exceptions caused by common things like a network error. 所以我在System.Net程序集中使用HttpWebRequest API,但由于C#没有检查异常,我不知道在哪里放置我的try-catch块来正确处理由网络错误等常见事件引起的不可避免的异常。 You know, in Java we would call these plain old checked IOExceptions . 你知道,在Java中我们会调用这些普通的旧的IOExceptions

This is what I have so far. 这就是我到目前为止所拥有的。 Are my try-catch blocks properly set up to handle network errors? 我的try-catch块是否正确设置以处理网络错误? Am I wrapping the right method calls? 我正在包装正确的方法调用吗? Looking at the documentation, I think they are right, but I need a second pair of eyes. 看文档,我认为它们是正确的,但我需要第二双眼睛。

HttpWebRequest request = WebRequest.CreateHttp(url);
request.Method = "POST";
request.BeginGetRequestStream(getRequestResult =>
            {
                HttpWebRequest getRequestRequest = (HttpWebRequest) getRequestResult.AsyncState;
                try
                {
                    Stream requestStream = getRequestRequest.EndGetRequestStream(getRequestResult);
                    requestStream.Write(parametersData, 0, parametersData.Length);
                    requestStream.Dispose();
                    getRequestRequest.BeginGetResponse(getResponseResult =>
                        {
                            HttpWebRequest getResponseRequest = (HttpWebRequest)getResponseResult.AsyncState;
                            try
                            {
                                WebResponse response = getResponseRequest.EndGetResponse(getRequestResult);
                                Stream responseStream = response.GetResponseStream();
                                StreamReader reader = new StreamReader(responseStream);
                                string jsonString = reader.ReadToEnd();
                                reader.Dispose();
                                JObject jsonObject = JObject.Parse(jsonString);
                                onResult(StatusCode.Ok, jsonObject);
                            }
                            catch (WebException)
                            {
                                onResult(StatusCode.NetworkError);
                            }
                        }, getRequestRequest);
                }
                catch (IOException)
                {
                    onResult(StatusCode.NetworkError);
                }
            }, request);

First off, unless there's some reason that you need to use HttpWebRequest , then you're better off using WebClient.UploadString instead, or any of WebClient's other UploadXXX overloads for uploading name/value pairs, files, binary data, etc. This will be much easier for you, and easier to troubleshoot and debug. 首先,除非有某些原因需要使用HttpWebRequest ,否则最好使用WebClient.UploadString ,或者任何WebClient的其他UploadXXX重载来上传名称/值对,文件,二进制数据等。这将是更容易,更容易进行故障排除和调试。 Also, another problem is that you're treating exceptions during JSON parsing or during your onResult handler error as network errors. 另外,另一个问题是您在JSON解析期间或在onResult处理程序错误期间将异常视为网络错误。

Below are three examples of using WebClient that you might want to try: a synchronous version, an "old-style" async version, and a "new-style" async version that uses async / await . 下面是使用您可能想要尝试的WebClient的三个示例:同步版本,“旧式”异步版本和使用async / await的“新式”异步版本。 All three versions also try to fix the exception handling issue that I noted above. 所有三个版本也尝试修复我上面提到的异常处理问题。 If you don't need async support, then the first version will be easiest. 如果您不需要异步支持,那么第一个版本将是最简单的。

static void PostSync (string url, string parametersData)
{
    using (WebClient wc = new WebClient())
    {
        wc.Headers[HttpRequestHeader.ContentType] = "application/x-www-form-urlencoded"; // or "application/json" or ...
        try
        {
            string htmlResult = wc.UploadString(url, parametersData);  // or UploadValues, UploadFile, ... 
            JObject jsonObject = null;
            try
            {
                jsonObject = JObject.Parse(htmlResult);
            }
            catch (JsonException ex)
            {
                onResult(StatusCode.JsonError);
            }
            onResult(StatusCode.Ok, jsonObject);

        }
        catch (System.Net.WebException ex)
        {
            onResult(StatusCode.NetworkError);
        }
    }
}

static void PostAsync(string url, string parametersData)
{
    using (WebClient wc = new WebClient())
    {
        wc.UploadStringCompleted += (Object sender, UploadStringCompletedEventArgs e) =>
        {
            if (e.Error != null)
                onResult(StatusCode.NetworkError);
            JObject jsonObject = null;
            try
            {
                jsonObject = JObject.Parse(e.Result);
            }
            catch (JsonException ex)
            {
                onResult(StatusCode.JsonError);
            }
            onResult(StatusCode.Ok, jsonObject);
        };
        try
        {
            wc.UploadStringAsync(new Uri(url, UriKind.Absolute), parametersData);
        }
        catch (System.Net.WebException ex)
        {
            onResult(StatusCode.NetworkError);
        }
    }
}

static async void PostTaskAsync(string url, string parametersData)
{
    using (WebClient wc = new WebClient())
    {
        wc.Headers[HttpRequestHeader.ContentType] = "application/x-www-form-urlencoded"; // or "application/json" or ...
        try
        {
            string htmlResult = await wc.UploadStringTaskAsync(url, parametersData);  // or UploadValues, UploadFile, ... 
            JObject jsonObject = null;
            try
            {
                jsonObject = JObject.Parse(htmlResult);
            }
            catch (JsonException ex)
            {
                onResult(StatusCode.JsonError);
            }
            onResult(StatusCode.Ok, jsonObject);

        }
        catch (System.Net.WebException ex)
        {
            onResult(StatusCode.NetworkError);
        }
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM