我正在尝试使用httpclient以base64格式上传图像,有人对此有经验吗?
using (var client = new HttpClient())
{
client.DefaultRequestHeaders.Accept.Clear();
client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
var detect = new Dictionary<string, string>
{
{ "api_key", API_KEY },
{ "api_secret", API_SECRET },
{ "urls", _base64 }
};
var content = new FormUrlEncodedContent(detect);
var response = await client.PostAsync(DETECT_URL, content);
HttpStatusCode _statusCode = response.StatusCode;
}
以上代码返回BadRequest,请帮助
非常感谢
唐
答案 0 :(得分:1)
a,
FormUrlEncodedContent
是application/x-www-form-urlencoded
而不是application/json
。
b,
如果加载了图像,则可以使用以下命令将其转换为base64:
public string ImageToBase64(Image image)
{
using (MemoryStream m = new MemoryStream())
{
image.Save(m, image.RawFormat);
byte[] imageBytes = m.ToArray();
// Convert byte[] to Base64 String
string base64String = Convert.ToBase64String(imageBytes);
return base64String;
}
}