c# HttpClient实现对http接口Get、Post表单请求

环境安装

在NuGet资源包管理器上下载资源包:
1 visual studio2022 打开NuGet资源包管理器:
c# HttpClient实现对http接口Get、Post表单请求
2. 安装webAPI Client
c# HttpClient实现对http接口Get、Post表单请求
3. 安装Multipart Reader
c# HttpClient实现对http接口Get、Post表单请求
4. 安装Json.Net
c# HttpClient实现对http接口Get、Post表单请求

c# 实现Post form-data文件上传

internal class HttpClientUtils
    {
        public static string PostData(string filePath, string filename)
        {
            string str = "";
            Console.WriteLine(ConfigurationManager.AppSettings["ftpIP"]);
            try
            {
                HttpClient client = new HttpClient();
                var postContent = new MultipartFormDataContent();  // 提交表单内容
                //postContent.Headers.ContentType = MediaTypeHeaderValue.Parse("multipart/form-data");  // 表头格式
                FileStream fileStream = File.Open(filePath, FileMode.Open, FileAccess.Read);  // 打开文件读取数据流
                //postContent.Headers.ContentLength = fileStream.Length;  //  文件大小
                postContent.Add(new StreamContent(fileStream), "file", filename);

                HttpResponseMessage response = client.PostAsync(ConfigurationManager.AppSettings["ftpIP"], postContent).Result;  // 提交表单信息
                str = response.Content.ReadAsStringAsync().Result;
                //fileStream.Close();
            }
            catch (Exception ex)
            {
                throw ex;
            }
            return str;
        }
    }
上一篇:《从问题到程序:用Python学编程和计算》——3.4 定义函数


下一篇:[LeetCode] 970. Powerful Integers 强力数字