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(); } } }