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);
            }
    
  • 相关阅读:
    查询已存入数据库中的图片,并显示出来
    图像插值的缺点
    windows网络服务之配置网络负载均衡(NLB)群集
    QR 码的位置检测符
    二维条码识别系统设计原理
    教你看懂Code128条形码
    DataMatrix二维条码源码分析检测识别图像位置
    C#条形码生成(五)----Web下的测试
    C# 生产成条形码3种方法
    屏蔽弹出对话框
  • 原文地址:https://www.cnblogs.com/Saints/p/12795791.html
Copyright © 2011-2022 走看看