zoukankan      html  css  js  c++  java
  • HTTPClient以WebAPI方式发送formData数据上传文件

    Net以WebAPI形式发送fromData格式的数据上传文件,示例代码如下:

     public static async Task<HttpResponseMessage> HttpPostFileAsync(string url, BearerToken token, BillReconcileFileTenant billReconcile, string filePath)
            {
                using (var httpClient = new HttpClient() { BaseAddress = new Uri(baseAddress) })
                {
                    httpClient.DefaultRequestHeaders.Accept.Clear();
                    httpClient.DefaultRequestHeaders.Authorization
                               = new AuthenticationHeaderValue("Bearer", token.access_token);
                    using (Stream fileStream = new FileStream(filePath, FileMode.Open, FileAccess.Read))
                    {
                        MultipartFormDataContent formData = new MultipartFormDataContent();
                        formData.Add(new StringContent(billReconcile.TenantName), ""TenantName"");// 使用""来转义
                        formData.Add(new StringContent(billReconcile.BillDate), ""BillDate"");
                        formData.Add(new StringContent(billReconcile.Count.ToString()), ""Count"");
                        formData.Add(new StringContent(billReconcile.Amount.ToString()), ""Amount"");
                        formData.Add(new StreamContent(fileStream, (Int32)fileStream.Length), "Data", billReconcile.FileName);
                        HttpResponseMessage response = await httpClient.PostAsync(url, formData);
                        if (!response.IsSuccessStatusCode)
                        {
                            LogUtil.Error($"{DateTime.Now.ToString()}对账接口对账失败,返回状态码为:{Convert.ToInt32(response.StatusCode)}");
                        }
                        else
                        {
                            LogUtil.Info($"{DateTime.Now.ToString()}对账接口Post请求成功,返回状态码为:{Convert.ToInt32(response.StatusCode)}");
                        }
                        return response;
                    }
                }
            }

    注意:BaseAddress和url使用时是BaseAddress+url为请求地址再去使用。

  • 相关阅读:
    吃货联盟项目
    字串符笔记
    带有参的方法
    js:自动亮起100盏灯
    JS字面量创建方式的优缺点
    为什么说对象字面量赋值比new Object()高效?
    javascript 字面量
    vue学习(一)、Vue.js简介
    Redis(二):c#连接Redis
    Redis(一):centos下安装。
  • 原文地址:https://www.cnblogs.com/Arainzhe/p/14049129.html
Copyright © 2011-2022 走看看