我有一个后台工作线程,它不断地与远程服务器同步数据。当我第一次运行该应用程序时,一切似乎都运行良好。它大约每 30 秒发出一次 Web 请求,并且数据成功返回。
如果我让模拟器运行很长时间,最终请求将失败并出现 (400) 错误请求。并且所有后续请求都做同样的事情。如果我杀死应用程序并重新启动它......一切都很好。
有人有想法么?代码如下。
public RestResponse<T> Execute<T>(RestRequest request) {
var restResponse = new RestResponse<T>();
var serializer = new JavaScriptSerializer();
var urlPath = baseUrl + "/" + request.Resource;
Console.WriteLine("Requesting: " + urlPath);
var httpRequest = (HttpWebRequest)HttpWebRequest.Create(new Uri(urlPath));
httpRequest.Headers = request.Headers;
foreach (string key in clientHeaders.Keys)
httpRequest.Headers.Add(key, clientHeaders[key]);
httpRequest.Headers.Add("Accept-Encoding", "gzip,deflate");
Authenticator.Authenticate(httpRequest);
httpRequest.Method = request.Method.ToString();
HttpWebResponse httpResponse = null;
try {
if ((request.Method == Method.POST) && (!request.IsJsonPost))
SetPostData(httpRequest, request);
if ((request.Method == Method.POST) && (request.IsJsonPost)){
SetJsonPostData(httpRequest, request);
}
httpResponse = (HttpWebResponse)httpRequest.GetResponse();
var reader = new StreamReader(GetStreamForResponse(httpResponse));
var responseString = reader.ReadToEnd();
Console.WriteLine(responseString);
reader.Close();
restResponse.StatusCode = httpResponse.StatusCode;
restResponse.Headers = httpResponse.Headers;
restResponse.Data = serializer.Deserialize<T>(responseString);
restResponse.ResponseStatus = ResponseStatus.Completed;
httpResponse.Close();
} catch (WebException e) {
restResponse.ResponseStatus = ResponseStatus.Error;
restResponse.ErrorMessage = e.Message;
restResponse.ErrorException = e;
var webResponse = (HttpWebResponse)e.Response;
if (webResponse != null) {
restResponse.StatusCode = webResponse.StatusCode;
restResponse.Headers = webResponse.Headers;
}
if (restResponse.StatusCode != HttpStatusCode.NotModified)
Console.WriteLine("An exception occured:\r\n " + request.Resource + "\r\n" + e + "\r\n");
} catch (Exception ex) {
restResponse.ResponseStatus = ResponseStatus.Error;
restResponse.ErrorMessage = ex.Message;
restResponse.ErrorException = ex;
}
if (httpResponse != null)
httpResponse.Close();
return restResponse;
}
它在这一行失败:
httpResponse = (HttpWebResponse)httpRequest.GetResponse();
堆栈跟踪:
System.Net.WebException: The remote server returned an error: (400) Bad Request.
at System.Net.HttpWebRequest.CheckFinalStatus (System.Net.WebAsyncResult result) [0x002f2] in /Developer/MonoTouch/Source/mono/mcs/class/System/System.Net/HttpWebRequest.cs:1477
at System.Net.HttpWebRequest.SetResponseData (System.Net.WebConnectionData data) [0x00141] in /Developer/MonoTouch/Source/mono/mcs/class/System/System.Net/HttpWebRequest.cs:1300
请求永远不会到达远程服务器。