HttpWebRequest 时,不认图片的Content-Type。Content-Type 实际是有传的。
报错内容:{"code":"PARAM_ERROR","message":"电子小票图片类型必须是image/png或者image/jpg,请检查表单字段file中的Content-Type属性"}
后又换成 HttpClient,又报:
{"code":"SIGN_ERROR","detail":{"detail":{"issue":"sign not match"},"field":"signature","location":"authorization","sign_information":{"method":"POST","sign_message_length":98,"truncated_sign_message":"POST\n/v3/marketing/shopping-receipt/shoppingreceipts\n1664429854\n3f0ecffa77a440359db1b52279f81be1\n\n","url":"/v3/marketing/shopping-receipt/shoppingreceipts"}},"message":"错误的签名,验签失败"}
先用POSTMAN 调试,居然是通的。然后把URL的HTTPS 去掉,再用 Fiddler 抓包。Fiddler 抓包内容:
Content-Disposition: form-data; name="file"; filename="xp20220928173716.png"
Content-Type: image/png
和代码对比,Content-Disposition:和 form-data; 间有空格。form-data; 与 name 间有空格。 name="file"; 和 filename 间有空格。
照着改代码。
fileTemplate = "Content-Disposition: form-data; name=\"{0}\"; filename=\"{1}\"\r\nContent-Type: {2}\r\n\r\n";
之后就正常了。
fileTemplate 原始内容(无法上传的版本):
string fileTemplate = "Content-Disposition:form-data;name=\"{0}\";filename=\"{1}\"\r\nContent-Type:{2}\r\n\r\n";
END.
API 具体报错异常:
catch (WebException webEx2) { if (webEx2.Response != null) { HttpWebResponse hwr = webEx2.Response as HttpWebResponse; string exRsp = string.Empty; using (Stream stream = hwr.GetResponseStream()) { StreamReader sr = new StreamReader(stream); exRsp = sr.ReadToEnd(); } //throw new Exception(exRsp); MessageBox.Show(exRsp); //return; } //throw webEx2; }
要从 WebException 的message 中找。
图样说明:
name和filename 后边一定要有双引号,不然微信也接收不了。