我正在尝试使用 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"}
我通过查尔斯查看了原始请求,它似乎或多或少像文档所建议的那样。但是有一个小的区别。
Curl - 有效 - 产生如下所示的参数:
--------------------------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 增加相同的数量,它就可以工作!