0

这个例外怎么可能?

我正在调用谷歌服务,如下所示。我的日志发现我在线收到超时异常var requestStream = request.GetRequestStream();

我什至没有将它放在catch块内,因为我认为读取流是从字符串中获取的(它非常小)。那么,我怎样才能得到超时呢?谷歌服务器是否可能需要时间并且阅读速度很慢而我得到了这个?

// Google had issues with SSL certificates. We know address is good, so just kill validation
            // and trust any certificate it might have..
            ServicePointManager.ServerCertificateValidationCallback = (sender, certificate, chain, errors) => true;


// Prepare HTTPS request. 5 seconds timeout should be good for google.
            const string Uri = "https://android.apis.google.com/c2dm/send";
            var request = (HttpWebRequest)WebRequest.Create(Uri);
            request.Headers.Add("Authorization", "GoogleLogin auth=" + this.SecurityToken);
            request.ContentType = "application/x-www-form-urlencoded";
            request.Method = "POST";
            request.Timeout = 5000;

            // build the post string     
            var postString = new StringBuilder();
            postString.AppendFormat("registration_id={0}", recipientId);
            postString.AppendFormat("&data.payload={0}", message);
            postString.AppendFormat("&collapse_key={0}", collapseKey);

            // write the post-string as a byte array     
            var requestData = Encoding.ASCII.GetBytes(postString.ToString());
            request.ContentLength = requestData.Length;
            var requestStream = request.GetRequestStream();
            requestStream.Write(requestData, 0, requestData.Length);
            requestStream.Close();

            // Do the actual request and read the response stream  
            try
            {
                var response = request.GetResponse();
                var responseString = GetResponseString(response);
                response.Close();

                return responseString.Contains("id=") 
                    ? SendStatus.Ok 
                    : GetSendStatusFromResponse(responseString);
            }
            catch (WebException ex)
            {
                var webResponse = (HttpWebResponse)ex.Response;
                if (webResponse != null)
                {
4

1 回答 1

1

GetRequestStream打开一个连接并返回一个已经连接的流。您写入流中的任何内容都会立即在线路上输出。它首先没有完全缓冲(尽管几乎可以肯定会涉及一些缓冲)。

所以它可以超时是有道理的;它只是意味着无法建立 TCP 连接,因为那是建立连接的时间点。

于 2012-06-22T16:16:38.997 回答