此代码有效(在.NET的现代版本中):
public static string SendXMLFile(string xmlFilepath, string uri, int timeout)
{
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(uri);
request.KeepAlive = false;
request.ProtocolVersion = HttpVersion.Version10;
request.ContentType = "application/xml";
request.Method = "POST";
StringBuilder sb = new StringBuilder();
using (StreamReader sr = new StreamReader(xmlFilepath))
{
String line;
while ((line = sr.ReadLine()) != null)
{
sb.AppendLine(line);
}
byte[] postBytes = Encoding.UTF8.GetBytes(sb.ToString());
if (timeout < 0)
{
request.ReadWriteTimeout = timeout;
request.Timeout = timeout;
}
request.ContentLength = postBytes.Length;
request.KeepAlive = false;
request.ContentType = "application/x-www-form-urlencoded";
try
{
Stream requestStream = request.GetRequestStream();
requestStream.Write(postBytes, 0, postBytes.Length);
requestStream.Close();
using (var response = (HttpWebResponse)request.GetResponse())
{
return response.ToString();
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
request.Abort();
return string.Empty;
}
}
}
但是,尝试在Windows CE应用程序使用的DLL中使用它时,该应用程序与旧版本的Compact Framework和.NET绑定,存在一些问题。首先,我试图改变&#34; var&#34;显性类型;我试着改变这个:
using (var response = (HttpWebResponse)request.GetResponse())
......对此:
using (HttpWebResponse response = (HttpWebResponse)request.GetResponse())
......但这甚至不起作用 - &#34; HttpWebResponse&#34;展示了可怕的波浪形红色下划线综合症。
徘徊在波浪中,我看,&#39; 无法隐式转换类型&#39; HttpWebResponse&#39;到&#39; System.IDisposable&#39; &#39;
所以我改变了HttpWebResponse&#39;到&#39; System.IDisposable&#39;整条线都变得潦草。它真正需要什么 - 实现IDisposable的类?如果是的话,哪一个可用/我最好的选择?
我也遇到HttpWebRequest没有ReadWriteTimeout属性,而StringBuilder没有AppendLine()方法的问题。这些成员的旧版本是否会在紧急情况下做到?#34;
目前,我已经就AppendLine做了这个:
sb.Append(line);
sb.Append("\r\n");
...并且只是注释掉了ReadWriteTimout:
if (timeout < 0)
{
//request.ReadWriteTimeout = timeout;
request.Timeout = timeout;
...但至于IDisposable问题,我正在做一个相当公平的Stonewall Jackson模仿。
答案 0 :(得分:1)
我认为在旧版本中,HttpWebResponse
不是一次性的,这应该通过删除using
子句来解决。
答案 1 :(得分:1)
这样的事,也许?
HttpWebResponse response = null;
try
{
response = (HttpWebResponse)request.GetResponse();
return response.ToString();
}
finally
{
var disposableResponse = response as IDisposable;
if(disposableResponse != null) disposableResponse.Dispose();
}