C# 如何正确地将图像发布到URL?
我试图将一个图像发布到StockTwits API,但收到一个422错误,作为无法识别图像格式的响应。该图像是一个png文件,因此它应该是一个有效的文件格式。我试着用一个jpeg来做同样的回应 我是否对图像进行了错误编码,或者在C# 如何正确地将图像发布到URL?,c#,http,stocktwits,C#,Http,Stocktwits,我试图将一个图像发布到StockTwits API,但收到一个422错误,作为无法识别图像格式的响应。该图像是一个png文件,因此它应该是一个有效的文件格式。我试着用一个jpeg来做同样的回应 我是否对图像进行了错误编码,或者在HttpClient中缺少一些配置 public void Share(string text, string imageFilePath) { using(HttpClient client = new HttpClient()) using (
HttpClient
中缺少一些配置
public void Share(string text, string imageFilePath)
{
using(HttpClient client = new HttpClient())
using (MultipartFormDataContent formData = new MultipartFormDataContent())
{
string url = stocktwitsCreateMessageUrl + "&" +
"body=" + Core.Globals.UrlEncode(twit) + "&" +
"sentiment=" + StockTwitsSentiment.ToString().ToLower();
byte[] imageBytes = File.ReadAllBytes(imageFilePath);
HttpContent imageContent = new ByteArrayContent(imageBytes);
string fileName = Path.GetFileName(imageFilePath);
formData.Add(imageContent, "chart", fileName);
HttpResponseMessage stockTwitsResponse = await client.PostAsync(url, formData);
Stream responseContent = await stockTwitsResponse.Content.ReadAsStreamAsync();
string result = new StreamReader(responseContent).ReadToEnd();
Print(result); // helper method
if (!stockTwitsResponse.IsSuccessStatusCode)
{
LogErrorResponse(result, stockTwitsResponse);
return;
}
else
LogAndPrint(typeof(Custom.Resource), "ShareStockTwitsSentSuccessfully", new[] { Name }, Cbi.LogLevel.Information);
}
}
答复:
{
“答复”:{“状态”:422}
“错误”:[{“消息”:“我们无法识别图像格式。格式必须为:image/jpg image/jpeg image/pjpeg image/png image/x-png image/gif”}]
}
别忘了将
内容类型
标题设置为“image/png”
请参阅:将内容类型添加到imageContent对象的标题解决了此问题。谢谢