1、Fiddler抓包参数详情
Content-Type: multipart/form-data; boundary="8d9ade1fd906a6a"
Content-Length: 39356
--8d9ade1fd906a6a
Content-Type: application/x-jpg
Content-Disposition: form-data; name=file; filename=test.jpg
...文件二进制流
--8d9ade1fd906a6a
Content-Disposition: form-data; name=toes
123@qq.com
--8d9ade1fd906a6a
Content-Disposition: form-data; name=subject
测试发送附件
--8d9ade1fd906a6a
Content-Disposition: form-data; name=Body
测试HttpClient发送文件+额外参数请求
--8d9ade1fd906a6a
2、使用MultipartFormDataContent封装文件和其它参数
上传文件时Content-Type是multipart/form-data,并且其它额外参数都要标识form-data
?2.1、把文件转成ByteArrayContent
private static ByteArrayContent CreateByteArrayContent(string key, string fileName, string fileContent,
byte[] fileBytes)
{
var fileByteArrayContent = new ByteArrayContent(fileBytes);
fileByteArrayContent.Headers.ContentType = new MediaTypeHeaderValue(fileContent);
fileByteArrayContent.Headers.ContentDisposition = new ContentDispositionHeaderValue("form-data")
{
Name = key, //接口匹配name
FileName = fileName //附件文件名
};
return fileByteArrayContent;
}
2.2、把其它附件参数转成ByteArrayContent
private static List<ByteArrayContent> CreateParamsByteArrayContent(IDictionary<string, string> dic)
{
var list = new List<ByteArrayContent>();
if (dic == null || dic.Count == 0) return list;
foreach (var (key, value) in dic)
{
var valueBytes = Encoding.UTF8.GetBytes(value);
var byteArray = new ByteArrayContent(valueBytes);
byteArray.Headers.ContentDisposition = new ContentDispositionHeaderValue("form-data")
{
Name = key
};
list.Add(byteArray);
}
return list;
}
2.3、构建MultipartFormDataContent
private static MultipartFormDataContent CreateContent(byte[] bytes,IDictionary<string,string> addParams)
{
var strBoundary = DateTime.Now.Ticks.ToString("x"); //分隔符
var resultContent = new MultipartFormDataContent(strBoundary);
//文件
var fileByteContent = CreateByteArrayContent("file", "test.jpg", "application/x-jpg", bytes);
resultContent.Add(fileByteContent);
//其它附加参数
var paramsByteContent = CreateParamsByteArrayContent(addParams);
paramsByteContent.ForEach(el =>
{
resultContent.Add(el);
});
return resultContent;
}
3、发送请求
static async Task Main(string[] args)
{
var dic = new Dictionary<string, string>
{
{"toes", "111@qq.com"},
{"subject", "测试发送附件"},
{"Body", "测试HttpClient发送文件+额外参数请求"},
};
var filePath = @"d:\image\shui.jpg";
using (var fileStream = File.Open(filePath, FileMode.Open))
{
var bytes = new byte[fileStream.Length];
fileStream.Read(bytes, 0, bytes.Length);
using (var client = new HttpClient())
{
var message = new HttpRequestMessage(HttpMethod.Post, "https://xxx/email/SendEmailIncludeAttach");
message.Content = CreateContent(bytes, dic);
var responseMessage = await client.SendAsync(message);
if (responseMessage.IsSuccessStatusCode)
{
var resStr = await responseMessage.Content.ReadAsStringAsync();
Console.WriteLine(resStr);
}
}
}
Console.ReadKey();
}
|