当使用MonoTouch时,如何处理/修复"获取响应流(ReadDone2)时出错:ReceiveFailure"?

Ada*_*nes 5 iphone mono httpwebrequest xamarin.ios

我正在使用MonoTouch构建iPhone应用程序.在应用程序中,我正在制作Web请求以从我们服务器上运行的Web服务中提取信息.

这是我构建请求的方法:

public static HttpWebRequest CreateRequest(string serviceUrl, string methodName, JsonObject methodArgs)
{
    string body = "";

    body = methodArgs.ToString();

    HttpWebRequest request = WebRequest.Create(serviceUrl) as HttpWebRequest;

    request.ContentLength = body.Length; // Set type to POST
    request.Method = "POST";
    request.ContentType = "text/json";
    request.Headers.Add("X-JSON-RPC", methodName);

    StreamWriter strm = new StreamWriter(request.GetRequestStream(), System.Text.Encoding.ASCII);
    strm.Write(body);
    strm.Close();

    return request;
}
Run Code Online (Sandbox Code Playgroud)

然后我称之为:

var request = CreateRequest(URL, METHOD_NAME, args);
request.BeginGetResponse (new AsyncCallback(ProcessResponse), request);
Run Code Online (Sandbox Code Playgroud)

而ProcessResponse看起来像这样:

private void ProcessResponse(IAsyncResult result)
{

    try 
    {
         HttpWebRequest request = (HttpWebRequest)result.AsyncState;

         using (HttpWebResponse response = (HttpWebResponse)request.EndGetResponse(result)) // this is where the exception gets thrown
         {
             using (StreamReader strm = new System.IO.StreamReader(response.GetResponseStream()))
             {
                 JsonValue value = JsonObject.Load(strm);

                 // do stuff...

                 strm.Close();
             } // using
             response.Close();
         } // using

         Busy = false;
     }
     catch(Exception e)
     {
         Console.Error.WriteLine (e.Message);
     }
}
Run Code Online (Sandbox Code Playgroud)

关于Monodroid的这个问题还有另一个问题,那里的答案建议明确关闭输出流.我试过这个,但它没有解决问题.我仍然遇到很多ReadDone2错误.

目前我的解决方法是在发生错误时重新提交Web请求,并且在大多数情况下第二次尝试似乎都有效.这些错误只发生在我在手机上测试时,并且在使用模拟器时从未发生过.

pou*_*pou 6

尽可能尝试使用,WebClient因为它会自动处理大量细节(包括流).它还可以更容易地使您的请求异步,这通常有助于不阻止UI.

例如,WebClient.UploadDataAsync看起来像是上面的一个很好的替代品.从UploadDataCompleted事件收到时,您将获得数据(此处为示例).

您是否确定您的请求始终只使用System.Text.Encoding.ASCIISystem.Text.Encoding.UTF8默认情况下,using 经常使用,因为它代表更多的字符.

更新:如果你发送或接收大量的byte [](或字符串),那么你应该看看使用OpenWriteAsync方法和OpenWriteCompleted事件.