如何在C#.NET中发送带附加图像的推送通知

时间:2018-02-24 20:23:34

标签: c# .net pushover

我尝试使用C#.NET通过 Pushover API 使用附加图像发送推送通知。以下代码返回json格式错误" 消息不能为空"。但是消息变量不是空的。由于SSL已过时,我尝试明确使用TLS 1.2。没有图像参数会出现相同的错误。

public async Task PushImage(string title, string message, Stream image, string userKey, string appKey)
{
    // This does not work - error "message cannot be blank"
    using (HttpClient httpClient = new HttpClient())
    {
        //specify to use TLS 1.2 as default connection
        ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12;

        MultipartFormDataContent form = new MultipartFormDataContent();
        form.Add(new StringContent(appKey), "token");
        form.Add(new StringContent(userKey), "user");
        form.Add(new StringContent(message), "message");
        var imageParameter = new StreamContent(image);
        imageParameter.Headers.ContentType = MediaTypeHeaderValue.Parse("image/png");
        form.Add(imageParameter, "attachment", "image.png");
        // Remove content type that is not in the docs
        foreach (var param in form)
            param.Headers.ContentType = null;

        HttpResponseMessage responseMessage = await httpClient.PostAsync(BaseApiUrl, form);
        if (responseMessage.IsSuccessStatusCode)
            return;

        string contentText = responseMessage.Content.ReadAsStringAsync().Result;
        var response = JsonConvert.DeserializeObject<PushResponse>(contentText);
        throw new ApplicationException(
            $"Push image request failed with status {(int)responseMessage.StatusCode} {responseMessage.StatusCode}: {response.Errors.JoinStrings(". ") ?? ""}");
    }
}

结果:

{"message":"cannot be blank","errors":["message cannot be blank"],"status":0,"request":"94152901-3b8f-45d6-ae6b-f7fc10b3439c"}

我通过Charles查看了原始请求,它或多或少似乎docs建议。然而,有一个小的差异。

卷曲 - 有效 - 产生如下所示的参数:

--------------------------30e0433d33c92cae
Content-Disposition: form-data; name="message"

my message
--------------------------30e0433d33c92cae--

HttpClient - 它还没有工作 - 为每个参数生成这个:

--70ae375f-ef30-4885-8a8a-d38363080024
Content-Disposition: form-data; name=message

my message
--70ae375f-ef30-4885-8a8a-d38363080024--

注意报价的差异。如果我拦截Charles中的邮件并将参数名称用双引号括起来,并将Content-Length增加相同的数量,就可以

1 个答案:

答案 0 :(得分:0)

事实证明需要将参数名称括在双引号中,如下所示:

form.Add(new StringContent(appKey), "\"token\"");
form.Add(new StringContent(userKey), "\"user\"");
form.Add(new StringContent(message), "\"message\"");
...
form.Add(imageParameter, "\"attachment\"", "image.png");
不要问我为什么。我只是想继续我的生活,忘了整整一天我都在调试这个问题......