4

所以我HttpWebRequest在 System.Net 程序集中使用 API,但是因为 C# 没有检查异常,我不确定将我的 try-catch 块放在哪里来正确处理由网络错误等常见问题引起的不可避免的异常。你知道,在 Java 中,我们称这些为普通的旧 check IOExceptions

这就是我到目前为止所拥有的。我的 try-catch 块是否正确设置以处理网络错误?我是否包装了正确的方法调用?看文档,我认为他们是对的,但我需要第二双眼睛。

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

1 回答 1

1

首先,除非出于某种原因需要使用HttpWebRequest,否则最好使用WebClient.UploadStringWebClient 的任何其他UploadXXX重载来上传名称/值对、文件、二进制数据等。这对你来说会容易得多,并且更容易进行故障排除和调试。此外,另一个问题是您在 JSON 解析期间或 onResult 处理程序错误期间将异常视为网络错误。

以下是您可能想尝试的三个使用 WebClient 的示例:同步版本、“旧式”异步版本和使用async/的“新式”异步版本await。所有三个版本还尝试修复我上面提到的异常处理问题。如果您不需要异步支持,那么第一个版本将是最简单的。

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);
        }
    }
}
于 2018-03-13T17:53:57.260 回答