示例#1
0
        protected HttpResponseMessage Wait(string statusCheckUrl, Task <HttpResponseMessage> task, ref uint requestId)
        {
            HttpResponseMessage response = null;

            try {
                while (true)
                {
                    response?.Dispose();

                    response = task.Result;

                    IEnumerable <string> headers;
                    if (response.Headers.TryGetValues("Request-Id", out headers))
                    {
                        requestId = SafeConvert.ToUInt32(headers.FirstOrDefault());
                    }
                    if (response.IsSuccessStatusCode)
                    {
                        Util.Assert(requestId != 0, "Request-Id должен быть указан");
                    }

                    if (response.StatusCode == HttpStatusCode.OK)
                    {
                        return(response);
                    }
                    if (response.StatusCode == HttpStatusCode.Accepted)
                    {
                        Reporter.Stage("Подготовка данных");
                        Token.WaitHandle.WaitOne(RequestInterval ?? Config.RequestInterval);
                        Token.ThrowIfCancellationRequested();
                        task = Client.GetAsync(statusCheckUrl, HttpCompletionOption.ResponseHeadersRead, Token);
                        continue;
                    }
                    //если это запрет то сервер может в теле передать причину
                    if (response.StatusCode == HttpStatusCode.Forbidden &&
                        response.Content.Headers.ContentType?.MediaType == "text/plain")
                    {
                        throw new EndUserError(response.Content.ReadAsStringAsync().Result);
                    }

                    if (response.StatusCode == HttpStatusCode.InternalServerError)
                    {
                        if (response.Content.Headers.ContentType?.MediaType == "text/plain")
                        {
                            throw new EndUserError(response.Content.ReadAsStringAsync().Result);
                        }
#if DEBUG
                        if (response.Content.Headers.ContentType?.MediaType == "application/json")
                        {
                            throw new Exception(response.Content.ReadAsAsync <DebugServerError>().Result.ToString());
                        }
#endif
                    }
                    throw new RequestException(
                              String.Format("Произошла ошибка при обработке запроса, код ошибки {0} {1}",
                                            response.StatusCode,
                                            response.Content.ReadAsStringAsync().Result),
                              response.StatusCode);
                }
            }
            catch (Exception) {
                response?.Dispose();
                throw;
            }
        }