如题,下面是我的两种代码,都是C#的。
第一种,使用HttpClient发送Post请求,该方法一直提示41005,缺少多媒体文件数据的错误,但是我用下面的代码请求我自己写的一些上传文件的接口都是可以正常获取到文件的;不知道是不是腾讯对这个接口的多媒体文件有什么特别的配置
public partial class HttpRepository : IHttpRepository
{
#region upload via file path
public virtual async Task<string> UploadFileAsync(string requestUrl, string fileName) => await HttpUploadFileAsync(requestUrl, fileName);
public virtual async Task<string> UploadFileAsync(string requestUrl, string fileName, string formName) => await HttpUploadFileAsync(requestUrl, fileName, formName);
public virtual async Task<string> UploadFileAsync(string requestUrl, string fileName, string formName, string additionInfo) => await HttpUploadFileAsync(requestUrl, fileName, formName, additionInfo);
async Task<string> HttpUploadFileAsync(string url, string filePath, string formName = "files", string additionInfo = "")
{
using (var client = _clientFactory.CreateClient())
{
var file = new FileInfo(filePath);
byte[] buffur = File.ReadAllBytes(filePath);
string boundary = DateTime.Now.Ticks.ToString("X");
using (var formData = new MultipartFormDataContent(boundary))
{
ByteArrayContent fileContent = new ByteArrayContent(buffur);
fileContent.Headers.ContentDisposition = new ContentDispositionHeaderValue("form-data")
{
Name = formName,
FileName = file.Name
};
fileContent.Headers.ContentType = new MediaTypeHeaderValue("application/octet-stream");
formData.Add(fileContent, formName, file.Name);
var response = await client.PostAsync(url, formData);
if (response.IsSuccessStatusCode)
{
var result = await response.Content.ReadAsStringAsync();
return result;
}
else
{
throw new BadHttpResponseException(url, response.StatusCode);
}
}
}
}
#endregion
#region upload via file bytes
public virtual async Task<string> UploadFileAsync(string requestUrl, string fileName, byte[] fileBytes) => await HttpUploadFileAsync(requestUrl, fileName, fileBytes);
public virtual async Task<string> UploadFileAsync(string requestUrl, string fileName, byte[] fileBytes, string formName) => await HttpUploadFileAsync(requestUrl, fileName, fileBytes, formName);
public virtual async Task<string> UploadFileAsync(string requestUrl, string fileName, byte[] fileBytes, string formName, string additionInfo) => await HttpUploadFileAsync(requestUrl, fileName, fileBytes, formName, additionInfo);
async Task<string> HttpUploadFileAsync(string url, string fileName, byte[] fileBytes, string formName = "file", string additionInfo = "")
{
using (var client = _clientFactory.CreateClient())
{
string boundary = DateTime.Now.Ticks.ToString("X");
using (var formData = new MultipartFormDataContent(boundary))
{
ByteArrayContent fileContent = new ByteArrayContent(fileBytes);
fileContent.Headers.ContentDisposition = new ContentDispositionHeaderValue("form-data") { Name = formName, FileName = fileName };
fileContent.Headers.ContentType = new MediaTypeHeaderValue("application/octet-stream");
formData.Add(fileContent);
var response = await client.PostAsync(url, formData);
if (response.IsSuccessStatusCode)
{
var result = await response.Content.ReadAsStringAsync();
return result;
}
else
{
throw new BadHttpResponseException(url, response.StatusCode);
}
}
}
}
#endregion
}
第二种使用原生态的HttpWebRequest发送请求,自己拼接,这个代码请求微信的接口是没问题的正常上传了文件,所以想要知道一下为什么会是这样,有没有哪位高人给解惑一下?
public class HttpRepository2 : HttpRepository
{
public HttpRepository2(
IHttpClientFactory clientFactory,
ILogger<HttpRepository> logger) : base(clientFactory, logger)
{
}
#region upload via file path
public override async Task<string> UploadFileAsync(string requestUrl, string fileName) => await Task.Run(() => HttpUploadFile(requestUrl, fileName));
public override async Task<string> UploadFileAsync(string requestUrl, string fileName, string formName) => await Task.Run(() => HttpUploadFile(requestUrl, fileName, formName));
public override async Task<string> UploadFileAsync(string requestUrl, string fileName, string formName, string additionInfo) => await Task.Run(() => HttpUploadFile(requestUrl, fileName, formName, additionInfo));
string HttpUploadFile(string url, string path, string formName = "file", string additionInfo = "")
{
dynamic resultObject = new ExpandoObject();
resultObject.requestID = UtilRepository.GenerateRandomCode();
resultObject.method = "POST";
resultObject.url = url;
resultObject.requestContent = path;
resultObject.createdAt = DateTime.Now.ToString();
string content = "";
try
{
#region Upload
HttpWebRequest request = WebRequest.Create(url) as HttpWebRequest;
CookieContainer cookieContainer = new CookieContainer();
request.CookieContainer = cookieContainer;
request.AllowAutoRedirect = true;
request.Method = "POST";
string boundary = DateTime.Now.Ticks.ToString("X"); // 随机分隔线
request.ContentType = "multipart/form-data;boundary=" + boundary;
byte[] itemBoundaryBytes = Encoding.UTF8.GetBytes("\r\n--" + boundary + "\r\n");
byte[] endBoundaryBytes = Encoding.UTF8.GetBytes("\r\n--" + boundary + "--\r\n");
int pos = path.LastIndexOf("\\");
string fileName = path.Substring(pos + 1);
StringBuilder sbHeader = new StringBuilder(string.Format("Content-Disposition:form-data;name=\"{0}\";filename=\"{1}\"\r\nContent-Type:application/octet-stream\r\n\r\n", formName, fileName));
byte[] postHeaderBytes = Encoding.UTF8.GetBytes(sbHeader.ToString());
FileStream fs = new FileStream(path, FileMode.Open, FileAccess.Read);
byte[] bArr = new byte[fs.Length];
fs.Read(bArr, 0, bArr.Length);
fs.Close();
Stream postStream = request.GetRequestStream();
postStream.Write(itemBoundaryBytes, 0, itemBoundaryBytes.Length);
postStream.Write(postHeaderBytes, 0, postHeaderBytes.Length);
postStream.Write(bArr, 0, bArr.Length);
byte[] bSplit = Encoding.UTF8.GetBytes("--" + boundary + "\r\n");
postStream.Write(bSplit, 0, bSplit.Length);
if (!string.IsNullOrEmpty(additionInfo))
{
byte[] additionBytes = Encoding.UTF8.GetBytes("Content-Disposition: form-data; name=\"description\";\r\n\r\n");
postStream.Write(additionBytes, 0, additionBytes.Length);
byte[] additionContentBytes = Encoding.UTF8.GetBytes(additionInfo);
postStream.Write(additionContentBytes, 0, additionContentBytes.Length);
postStream.Write(endBoundaryBytes, 0, endBoundaryBytes.Length);
}
postStream.Close();
HttpWebResponse response = request.GetResponse() as HttpWebResponse;
Stream instream = response.GetResponseStream();
StreamReader sr = new StreamReader(instream, Encoding.UTF8);
content = sr.ReadToEnd();
#endregion
resultObject.result = "success";
resultObject.resultContent = content;
string json = JsonConvert.SerializeObject(resultObject);
_logger.LogInformation(json);
}
catch (Exception ex)
{
resultObject.result = "fail";
resultObject.resultContent = ex.Message;
string json = JsonConvert.SerializeObject(resultObject);
_logger.LogInformation(json);
throw ex;
}
return content;
}
#endregion
#region upload via file bytes
public override async Task<string> UploadFileAsync(string requestUrl, string fileName, byte[] fileBytes) => await Task.Run(() => HttpUploadFile(requestUrl, fileName, fileBytes));
public override async Task<string> UploadFileAsync(string requestUrl, string fileName, byte[] fileBytes, string formName) => await Task.Run(() => HttpUploadFile(requestUrl, fileName, fileBytes, formName));
public override async Task<string> UploadFileAsync(string requestUrl, string fileName, byte[] fileBytes, string formName, string additionInfo) => await Task.Run(() => HttpUploadFile(requestUrl, fileName, fileBytes, formName, additionInfo));
string HttpUploadFile(string url, string fileName, byte[] fileBytes, string formName = "file", string additionInfo = "")
{
dynamic resultObject = new ExpandoObject();
resultObject.requestID = UtilRepository.GenerateRandomCode();
resultObject.method = "POST";
resultObject.url = url;
resultObject.requestContent = fileName;
resultObject.createdAt = DateTime.Now.ToString();
string content = "";
try
{
#region Upload
HttpWebRequest request = WebRequest.Create(url) as HttpWebRequest;
CookieContainer cookieContainer = new CookieContainer();
request.CookieContainer = cookieContainer;
request.AllowAutoRedirect = true;
request.Method = "POST";
string boundary = DateTime.Now.Ticks.ToString("X"); // 随机分隔线
request.ContentType = "multipart/form-data;charset=utf-8;boundary=" + boundary;
byte[] itemBoundaryBytes = Encoding.UTF8.GetBytes("\r\n--" + boundary + "\r\n");
byte[] endBoundaryBytes = Encoding.UTF8.GetBytes("\r\n--" + boundary + "--\r\n");
StringBuilder sbHeader = new StringBuilder(string.Format("Content-Disposition:form-data;name=\"{0}\";filename=\"{1}\"\r\nContent-Type:application/octet-stream\r\n\r\n", formName, fileName));
byte[] postHeaderBytes = Encoding.UTF8.GetBytes(sbHeader.ToString());
Stream postStream = request.GetRequestStream();
postStream.Write(itemBoundaryBytes, 0, itemBoundaryBytes.Length);
postStream.Write(postHeaderBytes, 0, postHeaderBytes.Length);
postStream.Write(fileBytes, 0, fileBytes.Length);
byte[] bSplit = Encoding.UTF8.GetBytes("--" + boundary + "\r\n");
postStream.Write(bSplit, 0, bSplit.Length);
if (!string.IsNullOrEmpty(additionInfo))
{
byte[] additionBytes = Encoding.UTF8.GetBytes("Content-Disposition: form-data; name=\"description\";\r\n\r\n");
postStream.Write(additionBytes, 0, additionBytes.Length);
byte[] additionContentBytes = Encoding.UTF8.GetBytes(additionInfo);
postStream.Write(additionContentBytes, 0, additionContentBytes.Length);
postStream.Write(endBoundaryBytes, 0, endBoundaryBytes.Length);
}
postStream.Close();
HttpWebResponse response = request.GetResponse() as HttpWebResponse;
Stream instream = response.GetResponseStream();
StreamReader sr = new StreamReader(instream, Encoding.UTF8);
content = sr.ReadToEnd();
#endregion
resultObject.result = "success";
resultObject.resultContent = content;
string json = JsonConvert.SerializeObject(resultObject);
_logger.LogInformation(json);
}
catch (Exception ex)
{
resultObject.result = "fail";
resultObject.resultContent = ex.Message;
string json = JsonConvert.SerializeObject(resultObject);
_logger.LogInformation(json);
throw ex;
}
return content;
}
#endregion
}