【HttpClient】请求微信内容安全的图片检测接口
前言
使用HttpClient去请求微信内容安全的图片检测接口,验证图片的合法性
微信接口接口文档地址:
https://developers.weixin.qq.com/miniprogram/dev/api-backend/open-api/sec-check/security.imgSecCheck.html
请求代码
/// <summary>
/// 调用微信内容安全的图片信息检查
/// </summary>
/// <param name="access_token">微信小程序请求接口access_token</param>
/// <param name="file">文件信息</param>
/// <returns></returns>
public async Task<string> ImgSecCheck(string access_token, Microsoft.AspNetCore.Http.IFormFile file)
{
string url = $"https://api.weixin.qq.com/wxa/img_sec_check?access_token={access_token}";
HttpResponseMessage response = null;
using (Stream fs = file.OpenReadStream())
{
//原文件生成的字节数组
byte[] fileBytes = new byte[fs.Length];
fs.Read(fileBytes, 0, fileBytes.Length);
var byteFileContent = new ByteArrayContent(fileBytes);
byteFileContent.Headers.ContentType = new MediaTypeHeaderValue("application/octet-stream");//指定Content-Type
byteFileContent.Headers.ContentDisposition = ContentDispositionHeaderValue.Parse($"form-data; name=\"fileName\"; filename=\"{file.FileName}\"");
response = await _client.PostAsync(url, byteFileContent);
}
string r = string.Empty;
if (response.IsSuccessStatusCode)
r = await response.Content.ReadAsStringAsync();
return r;
}
错误代码
/// <summary>
/// 上传文件
/// </summary>
/// <param name="access_token"></param>
/// <param name="file"></param>
/// <returns></returns>
public async Task<MessageModel<string>> UploadFile(string access_token, Microsoft.AspNetCore.Http.IFormFile file)
{
string url = $"https://api.weixin.qq.com/wxa/img_sec_check?access_token={access_token}";
MessageModel<string> result = new MessageModel<string>(false, "响应失败");
using (var content = new MultipartFormDataContent())
{
using (Stream fs = file.OpenReadStream())
{
//原文件生成的字节数组
byte[] fileBytes = new byte[fs.Length];
fs.Read(fileBytes, 0, fileBytes.Length);
content.Add(new ByteArrayContent(fileBytes), "fileName", file.FileName);
HttpResponseMessage response = await _client.PostAsync(url, content);
string r = string.Empty;
if (response.IsSuccessStatusCode)
r = await response.Content.ReadAsStringAsync();
result.Code = 200;
result.Msg = "上传成功";
result.Data = r;
}
}
return result;
}

浙公网安备 33010602011771号