【问题标题】:How to post image to URL properly?如何正确将图像发布到 URL?
【发布时间】:2016-01-05 17:39:03
【问题描述】:

我正在尝试将图像发布到 StockTwits API 并收到 422 错误作为响应,表示无法识别图像格式。图像是 png 文件,因此它应该是有效的文件格式。我尝试使用具有相同响应的 jpeg。

我是否对图像进行了错误编码,或者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},

"errors": [ { "message": "我们无法识别图像格式。格式必须是以下之一:image/jpg image/jpeg image/pjpeg image/png image/x-png image/gif" } ]

}

【问题讨论】:

    标签: c# http stocktwits


    【解决方案1】:

    别忘了将Content-Type 标头设置为"image/png"

    见:https://msdn.microsoft.com/en-us/library/system.net.httpwebrequest.contenttype(v=vs.110).aspx

    【讨论】:

    • 将内容类型添加到 imageContent 对象的标头解决了该问题。谢谢!
    猜你喜欢
    • 2016-11-14
    • 1970-01-01
    • 1970-01-01
    • 2021-11-09
    • 1970-01-01
    • 1970-01-01
    • 2021-12-08
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多