外观
WebAPI传递大数据
在接口中传输图片进制流或BASE64字符串时,使用FormUrlEncodedContent处理参数时,可能会因为参数太长导致异常无效的URL:URL字符串太长
FormUrlEncodedContent:使用application/x-www-form-urlencoded MIME类型编码的名称/值元组的容器,只能传输ContentType:application/x-www-form-urlencoded
实现:
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....)实现:
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;
}