1

我正在使用 WebClient 发布 XML 数据。

  public string uploadXMLData(string destinationUrl, string requestXml)
        {
            try
            {

                System.Uri uri = new System.Uri(destinationUrl);
                using (WebClient client = new WebClient())
                {
                    client.Headers.Add("content-type", "text/xml");
                    var response = client.UploadString(destinationUrl, "POST", requestXml); 
                }
            }

            catch (WebException webex)
            {

                WebResponse errResp = webex.Response;
                using (Stream respStream = errResp.GetResponseStream())
                {
                    StreamReader reader = new StreamReader(respStream);
                    string text = reader.ReadToEnd();
                }
            }
            catch (Exception e)
            { }

            return null;
        }

当出现错误时,我将其捕获为 WebException,并读取 Stream 以了解 XML 响应是什么。

我需要做的是将 XML 数据发布到异步中的 URL。所以我改变了功能:

public string uploadXMLData(string destinationUrl, string requestXml)
{
    try
    {

        System.Uri uri = new System.Uri(destinationUrl);
        using (WebClient client = new WebClient())
        {

            client.UploadStringCompleted
       += new UploadStringCompletedEventHandler(UploadStringCallback2); 
            client.UploadStringAsync(uri, requestXml);
        }
    }

    catch (Exception e)
    { }

    return null;
}


void UploadStringCallback2(object sender, UploadStringCompletedEventArgs e)
{            
    Console.WriteLine(e.Error);
}

我现在如何捕获 WebException 并读取 XML 响应?

我可以抛出 e.Error 吗?

任何帮助,将不胜感激

4

1 回答 1

2

我找到了解决方案:

   void UploadStringCallback2(object sender, UploadStringCompletedEventArgs e)
    {
        if (e.Error != null)
        {
            object objException = e.Error.GetBaseException();

            Type _type = typeof(WebException);
            if (_type != null)
            {
                WebException objErr = (WebException)e.Error.GetBaseException();
                WebResponse rsp = objErr.Response;
                using (Stream respStream = rsp.GetResponseStream())
                {
                    StreamReader reader = new StreamReader(respStream);
                    string text = reader.ReadToEnd();
                }
                throw objErr;
            }
            else
            {
                Exception objErr = (Exception)e.Error.GetBaseException();
                throw objErr;
            }
        }

     }
于 2015-07-14T12:46:29.943 回答