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为请求地址再去使用。

  • 相关阅读:
    Mybatis多层嵌套查询
    UUID 唯一性实现原理
    oracle 多实例启动
    orcal启动多实例是报 ORA-00845: MEMORY_TARGET not supported onthis system
    java调用quartz 2.2.2方法总结。
    mybatis中like的使用(模糊查询)
    Orcal数据库实现主键ID自增
    spring cloud分布式关于熔断器
    spring cloud分布式健康检查
    spring cloud分布式整合zipkin的链路跟踪
  • 原文地址:https://www.cnblogs.com/Arainzhe/p/14049129.html
Copyright © 2011-2022 走看看