【发布时间】:2013-06-19 15:29:56
【问题描述】:
我有一个使用 Monodevelop 用 C# 编写的 iOS 应用程序,作为应用程序的一部分,我调用了一个 Web 服务。 Web 服务调用要求将 JSON 数据写入请求。但是,我第一次尝试写入数据时收到错误消息;对具有相同参数的相同方法的所有后续调用都有效。以下是相关代码的sn-p:
// Start snippet
HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create (_connectionSettings.Uri);
request.Timeout = 15000; // milliseconds
if (_connectionSettings.Username != "") {
request.Credentials = new NetworkCredential (_connectionSettings.Username, _connectionSettings.Password);
}
if (post) {
request.Method = "POST";
request.ContentType = "application/json";
if (jsonData != null) {
byte[] byteArray = System.Text.Encoding.UTF8.GetBytes(jsonData);
request.ContentLength = byteArray.Length;
using (Stream ds = request.GetRequestStream()) { //<--- ERROR HERE
ds.Write (byteArray, 0, byteArray.Length);
}
} else {
request.Method = "GET";
}
using (HttpWebResponse response = (HttpWebResponse)request.GetResponse()) {
// end snippet
我得到的错误如下:
System.Net.WebException:请求被取消。 ---> 系统异常: 在写入所有字节之前无法关闭流 --- 内部异常堆栈跟踪结束 --- at
System.Net.WebConnectionStream.Close() [0x00121] 在
/Developer/MonoTouch/Source/mono/mcs/class/System/System.Net/WebConnectionStream.cs:785 在 System.IO.Stream.Dispose () [0x00000] 中
/Developer/MonoTouch/Source/mono/mcs/class/corlib/System.IO/Stream.cs:93 在
MyCustomMethod (System.String& responseString, System.String jsonData, Boolean post, Boolean suppressAlert) [0x00101] 在 /Path/To/My/Class.cs:192
有什么想法我可能做错了吗?
编辑
好的,显然在单步执行应用程序时,该方法每次都有效。我注意到的是,当抛出错误时, request.ContentLength 为零,尽管 byteArray.Length 不为零。但是,在单步执行应用程序时,request.ContentLength 会保持 byteArray.Length 的预期值。
【问题讨论】:
-
你可以尝试使用 (Stream ds = request.GetRequestStream()) { //
-
@srsyogesh,感谢您的回复。接受这些参数的 StreamWriter.Write 没有重载。但是,使用 ds.Write(byteArray) 会引发错误“System.Net.ProtocolViolationException - 要写入的字节数大于指定的 ContentLength。”似乎发生了我在编辑中指出的相同问题,特别是 request.ContentLength 的值为零,即使 byteArray.Length 不为零。
-
可以设置 request.ContentLength = byteArray.Length 来解决这个问题吗?不确定只是查看异常的想法,或者正如您在编辑中提到的那样,这两个值已经相同??
-
@srsyogesh 是的,在使用 (Stream ds = request.GetRequestStream()) 之前我设置了 request.ContentLength = byteArray.Length。在该位置放置一个断点,我看到 request.ContentLength 的值确实等于 byteArray.Length。但是,当我恢复应用程序并引发后续错误时,request.ContentLength 的值为零。有趣的是,如果我不恢复应用程序而是逐步执行应用程序,request.ContentLength 仍然等于 byteArray.Length,并且应用程序可以正常工作!去图吧。
标签: c# .net monodevelop xamarin