zoukankan      html  css  js  c++  java
  • HttpClient实现请求

     1  /// <summary>
     2         ///     HttpClient实现Get请求(异步)
     3         /// </summary>
     4         private static async void DoGet()
     5         {
     6             var url = "http://localhost:5555/api/Test/Get?id=1";
     7             //创建HttpClient(注意传入HttpClientHandler)  
     8             var handler = new HttpClientHandler {AutomaticDecompression = DecompressionMethods.GZip};
     9 
    10             using (var http = new HttpClient(handler))
    11             {
    12                 //await异步等待回应  
    13                 var response = await http.GetAsync(url);
    14                 //确保HTTP成功状态值  
    15                 response.EnsureSuccessStatusCode();
    16 
    17                 //await异步读取最后的JSON(注意此时gzip已经被自动解压缩了,因为上面的AutomaticDecompression = DecompressionMethods.GZip)  
    18                 Console.WriteLine(await response.Content.ReadAsStringAsync());
    19             }
    20         }
    21 
    22         /// <summary>
    23         ///     HttpClient实现Put请求(异步)
    24         /// </summary>
    25         private static async void DoPut()
    26         {
    27             var userId = 6;
    28             var url = "http://localhost:5555/api/put/register?userid=" + userId;
    29 
    30             //设置HttpClientHandler的AutomaticDecompression  
    31             var handler = new HttpClientHandler {AutomaticDecompression = DecompressionMethods.GZip};
    32             //创建HttpClient(注意传入HttpClientHandler)  
    33             using (var http = new HttpClient(handler))
    34             {
    35                 //使用FormUrlEncodedContent做HttpContent  
    36                 var content = new FormUrlEncodedContent(new Dictionary<string, string>
    37                 {
    38                     {"UserName", "修改胡景宝"},
    39                     {"UserEmail", "932329468@qq.com"} 
    40                 });
    41 
    42                 //await异步等待回应  
    43 
    44                 var response = await http.PutAsync(url, content);
    45                 //确保HTTP成功状态值  
    46                 response.EnsureSuccessStatusCode();
    47                 //await异步读取最后的JSON(注意此时gzip已经被自动解压缩了,因为上面的AutomaticDecompression = DecompressionMethods.GZip)  
    48                 Console.WriteLine(await response.Content.ReadAsStringAsync());
    49             }
    50         }
  • 相关阅读:
    TCP/IP的基本概念知识
    Mysql查询今天、昨天、7天、近30天、本月、上一月数据
    PHP OOP面向对象部分方法归总(代码实例子)
    PHP 变量
    PHP超级全局变量、魔术变量和魔术函数
    PHP编程效率的20个要点
    MemCache超详细解读
    CodeForces 652E Pursuit For Artifacts 边双连通分量
    HDU 2460 Network 边双连通分量 缩点
    HDU 3594 Cactus 有向仙人掌图判定
  • 原文地址:https://www.cnblogs.com/mandalaluo/p/7115684.html
Copyright © 2011-2022 走看看