在Windows Phone 8中,使用FormUrlEncodedContent()进行Post上传时,字符串过大。
在Windows Phone 8中,使用FormUrlEncodedContent()进行Post上传时,字符串过大。
我的代码:
string json = BuildJson(uploadItem); using (var client = new HttpClient()) { var values = new List>(); values.Add(new KeyValuePair ("parameter", json)); var content = new FormUrlEncodedContent(values); var response = await client.PostAsync(App.Current.LoginUrl, content); var responseString = await response.Content.ReadAsStringAsync(); }
我的json字符串包含一个base64编码的图片,所以`FormUrlEncodedContent`会抛出异常:
"无效的URI:URI字符串过长"。
重要的是,服务器期望的格式是"parameter"作为post键,json作为post值。我该如何绕过`FormUrlEncodedContent`的这个限制?
在Windows Phone 8中使用HttpClient的Post方法上传数据时,可能会遇到“String too large for FormUrlEncodedContent()”的问题。这个问题的原因是在使用FormUrlEncodedContent时,字符串的长度超过了其内部的限制。
解决这个问题的方法是使用自定义的方法替代FormUrlEncodedContent。下面是一个解决方法的示例代码:
// URI Escape JSON string var content = EscapeDataString(json); private string EscapeDataString(string str) { int limit = 2000; StringBuilder sb = new StringBuilder(); int loops = str.Length / limit; for (int i = 0; i <= loops; i++) { if (i < loops) { sb.Append(Uri.EscapeDataString(str.Substring(limit * i, limit))); } else { sb.Append(Uri.EscapeDataString(str.Substring(limit * i))); } } return sb.ToString(); }
需要注意的是,这个解决方法不适用于使用HttpClient的Assembly System.Net.Http版本1.5.0.0。