zoukankan      html  css  js  c++  java
  • 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);
            }
    
  • 相关阅读:
    LeetCode
    LeetCode
    LeetCode
    LeetCode
    剑指offer-栈的压入、弹出序列
    剑指offer-包含min函数的栈
    图-Dijkster最短路径
    剑指offer-顺时针打印矩阵
    二叉树的镜像
    剑指offer-树的子结构
  • 原文地址:https://www.cnblogs.com/Saints/p/12795791.html
Copyright © 2011-2022 走看看