HttpClient with Stream

使用Stream的好处

避免占内存较大的(字符串)中间变量的使用

实现

Get

        private async Task GetResourceWithStream(HttpClient httpClient)
        {
            var request = new HttpRequestMessage(HttpMethod.Get,"api/demos/123");
            request.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));

            using var response = await httpClient.SendAsync(request);
            response.EnsureSuccessStatusCode();

            using var stream = await response.Content.ReadAsStreamAsync();
            using var streamReader = new StreamReader(stream);
            using var jsonTextReader = new JsonTextReader(streamReader);
            var jsonSeriailzer = new JsonSerializer();
            var demo=jsonSeriailzer.Deserialize<Demo>(jsonTextReader);
        }

Post

        private async Task PostAndReadPosterWithStreams(HttpClient httpClient)
        {
            var random = new Random();
            var generatedBytes = new byte[524288];
            random.NextBytes(generatedBytes);

            var demoForCreation = new DemoForCreation()
            {
                Name = "Test Name",
                Bytes = generatedBytes
            };

            using MemoryStream memoryStream = new MemoryStream();
            using var streamWriter = new StreamWriter(memoryStream, new UTF8Encoding(), 1024, true);
            using var jsonTextWriter = new JsonTextWriter(streamWriter);
            var jsonSerializer = new JsonSerializer();
            jsonSerializer.Serialize(jsonTextWriter,demoForCreation);
            jsonTextWriter.Flush();

            memoryStream.Seek(0, SeekOrigin.Begin);

            using var request = new HttpRequestMessage(HttpMethod.Post,"api/demos");
            request.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
            request.Content = new StreamContent(memoryStream);
            request.Content.Headers.ContentType=new MediaTypeHeaderValue("application/json");

            var response = await httpClient.SendAsync(request);
            response.EnsureSuccessStatusCode();
            var content = await response.Content.ReadAsStringAsync();
            var demo = JsonConvert.DeserializeObject<Demo>(content);
        }
posted @ 2020-04-28 17:45  青玄鸟  阅读(467)  评论(0编辑  收藏  举报