HttpClient FormUrlEncodedContent System.UriFormatException: 无效的 URI: URI 字符串太长问题解决方案


1.问题描述:

HttpClint 使用FormUrlEncodedContent 调用接口时 报错 System.UriFormatException: 无效的 URI: URI 字符串太长;

2.解决:

using System;
using System.Collections.Generic;
using System.IO;
using System.IO.Compression;
using System.Linq;
using System.Net.Http;
using System.Text;
using System.Threading.Tasks;
using System.Web;

namespace PointToPoint
{
    class Program
    {
        static void Main(string[] args)
        {
            string data = "";

            byte[] buffer = System.Text.UTF8Encoding.UTF8.GetBytes(data);
            //压缩后的byte数组
            byte[] compressedbuffer = null;
            //Compress buffer,压缩缓存
            MemoryStream ms = new MemoryStream();
            using (GZipStream zs = new GZipStream(ms, CompressionMode.Compress, true))
            {
                zs.Write(buffer, 0, buffer.Length);
            }
            //只有GZipStream在Dispose后调应对应MemoryStream.ToArray()所得到的Buffer才是我们需要的结果
            compressedbuffer = ms.ToArray();
            //将压缩后的byte数组basse64字符串
            string text64 = Convert.ToBase64String(compressedbuffer);
            var content = HttpUtility.UrlEncode(text64);
            HttpClient client = new HttpClient();
            string d = "account=帐号&password=密码&content=" + System.Web.HttpUtility.UrlEncode(text64);

            var contenStr = new StringContent(d, Encoding.UTF8);
            contenStr.Headers.Remove("Content-Type");//必须
            contenStr.Headers.Add("Content-Type", "application/x-www-form-urlencoded");//1.根据需求设置
            string rlt = client.PostAsync("http://192.168.1.82/BatchSms.ashx", contenStr).Result.Content.ReadAsStringAsync().Result;
            //string rlt = client.SendAsync(request).Result.Content.ReadAsStringAsync().Result;
            Console.WriteLine(rlt);
            Console.ReadKey();
        }
    }
}

 


免责声明!

本站转载的文章为个人学习借鉴使用,本站对版权不负任何法律责任。如果侵犯了您的隐私权益,请联系本站邮箱yoyou2525@163.com删除。



 
粤ICP备18138465号  © 2018-2025 CODEPRJ.COM