我正在使用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,并读取流以了解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吗?
如能提供任何帮助,将不胜感激。
发布于 2015-07-14 12:46:29
我找到了解决办法:
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;
}
}
}https://stackoverflow.com/questions/31388171
复制相似问题