我正在使用 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 吗?
任何帮助,将不胜感激