zoukankan      html  css  js  c++  java
  • 【HttpClient】常用的3个请求方式

    前言

    经常用到,做个记录

    代码

            /// <summary>
            /// HttpGet请求
            /// </summary>
            /// <param name="url"></param>
            /// <returns></returns>
            static async Task<string> HttpGet(string url)
            {
                HttpResponseMessage response = await _client.GetAsync(url);
    
                string result = string.Empty;
                if (response.IsSuccessStatusCode)
                    result = await response.Content.ReadAsStringAsync();
    
                return result;
            }
    
            /// <summary>
            /// HttpPost请求,FromForm接收
            /// </summary>
            /// <param name="url"></param>
            /// <param name="dic"></param>
            /// <returns></returns>
            static async Task<string> HttpPostForm(string url, Dictionary<string, string> dic)
            {
                var httpContent = new MultipartFormDataContent();
                foreach (var para in dic)
                    httpContent.Add(new StringContent(para.Value), para.Key);
    
                HttpResponseMessage response = await _client.PostAsync(url, httpContent);
    
                string result = string.Empty;
                if (response.IsSuccessStatusCode)
                    result = await response.Content.ReadAsStringAsync();
    
                return result;
            }
    
            /// <summary>
            /// HttpPost请求,FromBody接收
            /// </summary>
            /// <param name="url"></param>
            /// <param name="dic"></param>
            /// <returns></returns>
            static async Task<string> HttpPostBody(string url, Dictionary<string, object> dic)
            {
                var p = System.Text.Json.JsonSerializer.Serialize(dic);//对象序列化为Json字符串
    
                HttpContent httpContent = new StringContent(p);
                httpContent.Headers.ContentType = new MediaTypeHeaderValue("application/json");
    
                HttpResponseMessage response = await _client.PostAsync(url, httpContent);
    
                string result = string.Empty;
                if (response.IsSuccessStatusCode)
                    result = await response.Content.ReadAsStringAsync();
    
                return result;
            }
  • 相关阅读:
    傻瓜教程:asp.net(c#) 如何配置authentication,完成基于表单的身份验证
    ajax与php交互的get和post两种实现方式
    php 存储过程
    一万小时天才理论
    servlet阅读
    post and get
    合并两个有序数组(重新开始)
    Java参数传递问题
    一万小时(如何实现)阅读
    java IO 流的学习(我们到底能走多远系列1)
  • 原文地址:https://www.cnblogs.com/masonblog/p/15637224.html
Copyright © 2011-2022 走看看