测试环境:wince 6.0 .Net Compact FrameWork
C# 客户端访问Http接口一般使用System.Net.WebRequest类实现,以下为关键代码:
Encoding encoding = Encoding.GetEncoding("utf-8");
string res=string.Empty;
//请求
WebRequest webRequest = null;
Stream postStream = null;
//响应
WebResponse webResponse = null;
StreamReader streamReader = null;
//请求
webRequest = WebRequest.Create(url);
webRequest.Proxy = new WebProxy();
webRequest.Method = "POST";
webRequest.Timeout = timeout;
webRequest.ContentType = ContentType;
//向请求流写数据
byte[] postData = encoding.GetBytes(data);
webRequest.ContentLength = postData.Length;
postStream = webRequest.GetRequestStream();
postStream.Write(postData, 0, postData.Length);
//响应
webResponse = webRequest.GetResponse();//1、此处在wince平台上报“在写入请求数据前,不能检索此请求的响应”
streamReader = new StreamReader(webResponse.GetResponseStream(), encoding);
res = streamReader.ReadToEnd();
一、问题上面代码在windows pc开发能正常运行,但在wince在代码webRequest.GetResponse()运行后会报“在写入请求数据前,不能检索此请求的响应”的错。
二、解决方案在写入数据后刷新及关闭流,即:
postStream.Write(postData, 0, postData.Length);
//必须加上以下代码
postStream.Flush();
postStream.Close();
如果觉得此篇文章对你有帮助,记得帮我点个赞^_^