コード例 #1
0
        private async Task <string> RequestStringAsync(Uri uri, bool checkCached)
        {
            Logger.Debug($"[{nameof(TumOnlineRequest)}] Request: {uri}");
            if (checkCached && (SERVICE.VALIDITY != TumOnlineService.VALIDITY_NONE))
            {
                string result = CacheDbContext.GetCacheLine(uri.ToString());
                if (!string.IsNullOrEmpty(result))
                {
                    Logger.Debug($"Loaded cached request for: '{uri}'");
                    return(result);
                }
                Logger.Debug($"No cached request found for: '{uri}'");
            }

            if (!NetworkHelper.Instance.ConnectionInformation.IsInternetAvailable)
            {
                Logger.Warn("Unable to request string - no internet.");
                return(null);
            }

            try
            {
                HttpClient client = new HttpClient();
                client.DefaultRequestHeaders.TryAppendWithoutValidation("User-Agent", GetUserAgent());
                HttpResponseMessage response = await client.GetAsync(uri);

                IHttpContent content = response.Content;
                IBuffer      buffer  = await content.ReadAsBufferAsync();

                using (DataReader dataReader = DataReader.FromBuffer(buffer))
                {
                    string result = dataReader.ReadString(buffer.Length);
                    if (SERVICE.VALIDITY != TumOnlineService.VALIDITY_NONE)
                    {
                        CacheDbContext.UpdateCacheLine(uri.ToString(), DateTime.Now.Add(SERVICE.VALIDITY), result);
                    }
                    Logger.Debug($"[{nameof(TumOnlineRequest)}] Response: {result}");
                    return(result);
                }
            }
            catch (Exception e)
            {
                Logger.Error("Failed to request string from: " + uri, e);
            }
            return(null);
        }