我试图使用http post从asp.net发布一些数据到webservice.
这样做我得到了封闭的错误.我检查过很多帖子,但没有什么可以帮助我.对此的任何帮助将非常感谢.
Length ='dataStream.Length'引发了类型'System.NotSupportedException'的异常
Position ='dataStream.Position'引发了类型'System.NotSupportedException'的异常
随函附上我的代码:
public XmlDocument SendRequest(string command, string request)
{
XmlDocument result = null;
if (IsInitialized())
{
result = new XmlDocument();
HttpWebRequest webRequest = null;
HttpWebResponse webResponse = null;
try
{
string prefix = (m_SecureMode) ? "https://" : "http://";
string url = string.Concat(prefix, m_Url, command);
webRequest = (HttpWebRequest)WebRequest.Create(url);
webRequest.Method = "POST";
webRequest.ContentType = "text/xml";
webRequest.ServicePoint.Expect100Continue = false;
string UsernameAndPassword = string.Concat(m_Username, ":", m_Password);
string EncryptedDetails = Convert.ToBase64String(Encoding.ASCII.GetBytes(UsernameAndPassword));
webRequest.Headers.Add("Authorization", "Basic " + EncryptedDetails);
using (StreamWriter sw = new StreamWriter(webRequest.GetRequestStream()))
{
sw.WriteLine(request);
}
// Assign the response object of 'WebRequest' to a 'WebResponse' variable.
webResponse = (HttpWebResponse)webRequest.GetResponse();
using (StreamReader sr = new StreamReader(webResponse.GetResponseStream()))
{
result.Load(sr.BaseStream);
sr.Close();
}
}
catch (Exception ex)
{
string ErrorXml = string.Format("<error>{0}</error>", ex.ToString());
result.LoadXml(ErrorXml);
}
finally
{
if (webRequest != null)
webRequest.GetRequestStream().Close();
if (webResponse != null)
webResponse.GetResponseStream().Close();
}
}
return result;
}
Run Code Online (Sandbox Code Playgroud)
提前致谢 !!
Ratika
当你调用HttpWebResponse.GetResponseStream
,它返回一个Stream
实现是在没有任何召回的能力; 换句话说,从HTTP服务器发送的字节将直接发送到此流以供使用.
这与一个FileStream
实例的不同之处在于,如果您想要读取已经通过流消耗的文件的一部分,则可以始终将磁头移回到该位置以从中读取文件(很可能,它在内存中缓冲,但你得到了重点).
使用HTTP响应,您必须实际重新发出请求到服务器才能再次获得响应.因为这种反应是不能保证是相同的,大部分的位置相关的方法和属性(例如Length
,Position
,Seek
上)Stream
执行回传给你扔NotSupportedException
.
如果您需要在向后移动Stream
,那么你应该创建一个MemoryStream
实例和响应复制Stream
到MemoryStream
通过CopyTo
方法,就像这样:
using (var ms = new MemoryStream())
{
// Copy the response stream to the memory stream.
webRequest.GetRequestStream().CopyTo(ms);
// Use the memory stream.
}
Run Code Online (Sandbox Code Playgroud)
请注意,如果你不使用.NET 4.0或更高版本(其中CopyTo
在Stream
引入类),那么你可以手动复制流.
归档时间: |
|
查看次数: |
27909 次 |
最近记录: |