tnblog
首页
视频
资源
登录
有个性,不需要签名
排名
6
文章
6
粉丝
16
评论
8
{{item.articleTitle}}
{{item.blogName}} : {{item.content}}
ICP备案 :渝ICP备18016597号-1
网站信息:2018-2024TNBLOG.NET
技术交流:群号656732739
联系我们:contact@tnblog.net
欢迎加群交流技术

WebAPI传递大数据

8586人阅读 2019/6/12 9:55 总访问:223717 评论:0 收藏:1 手机
分类: .NET

在接口中传输图片进制流或BASE64字符串时,使用FormUrlEncodedContent处理参数时,可能会因为参数太长导致异常无效的URL:URL字符串太长

  • FormUrlEncodedContent:使用application/x-www-form-urlencoded MIME类型编码的名称/值元组的容器,只能传输ContentType:application/x-www-form-urlencoded

实现:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
public async Task<string> Post(string url, Dictionary<string, string> param)
       {
           string result="";
           HttpClient click = new HttpClient();
           HttpContent postContent = new FormUrlEncodedContent(param);
           try
           {
               var respMsg = await click.PostAsync(url, postContent);
               respMsg.EnsureSuccessStatusCode();
               result = await respMsg.Content.ReadAsStringAsync();
           }
           catch (HttpRequestException ex)
           {
               result = ex.Message;
           }
           return result;
       }

可是当param太大时 new FormUrlEncodedContent(param)就会抛出异常无效的URL:URL字符串太长


可以换一种方式实现  StringContent!

  • StringContent:基于字符串提供http的内容,传输类型皆可(比如常用的application/x-www-form-urlencoded、application/json、multipart/form-data….)

    实现:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
public async Task<string> Post(string url, Dictionary<string, string> param)
       {
           string result="";
           HttpClient click = new HttpClient();
           var urlcode = HttpHelp.DicToFormCode(param); //需要把键值对转为urlencoded
           StringContent postContent = new StringContent(urlcode, Encoding.UTF8, "application/x-www-form-urlencoded");
           try
           {
               var respMsg = await click.PostAsync(url, postContent);
               respMsg.EnsureSuccessStatusCode();
               result = await respMsg.Content.ReadAsStringAsync();
           }
           catch (HttpRequestException ex)
           {
               result = ex.Message;
           }
           return result;
       }

static string DicToFormCode(Dictionary<string, string> param)
       {
           string pc = "";

           foreach (var p in param)
           {
               pc += HttpUtility.UrlEncode(p.Key);
               if (p.Value.GetType() == typeof(object[]))
                   pc += "=" + HttpUtility.UrlEncode(JsonConvert.SerializeObject(p.Value)) + "&";
               else
                   pc += "=" + HttpUtility.UrlEncode(p.Value.ToString()) + "&";
           }
           pc = pc.TrimEnd('&');

           return pc;
       }





欢迎加群讨论技术,1群:677373950(满了,可以加,但通过不了),2群:656732739

评价