我有一个后台工作线程,它不断地将数据同步到远程服务器或从远程服务器同步数据。当我第一次运行应用程序时,一切似乎都正常。它每隔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
请求永远不会到达远程服务器。
答案 0 :(得分:2)
问题发生在clientHeaders
集合中。在应用程序生命周期中,此RESTClient
类将实例化一次。我一遍又一遍地添加标题而不是先清除它们。过了一会儿,标题太大了,发出了错误的请求。
答案 1 :(得分:0)
我假设你的连接用完了。您可以尝试增加它们:
<configuration>
<system.net>
<connectionManagement>
<add address="*" maxconnection="65535" />
</connectionManagement>
</system.net>
</configuration>