我们有一个访问外部API以获取和下载PDF文件的过程。 以下是过程:
using (var client = new WebClient())
{
client.BaseAddress = add;
client.Encoding = System.Text.Encoding.UTF8;
client.Headers[HttpRequestHeader.ContentType] = "application/pdf";
client.Headers.Add(HttpRequestHeader.Authorization, "Basic ");
JObject jobject = generateReportPDFRequest(report.ReportID);
//string tst = jobject.ToString();
string result = client.UploadString(add, "POST", jobject.ToString());
if (!string.IsNullOrEmpty(result))
{
retval = AddReportPDF(reportid, Encoding.ASCII.GetBytes(result));
}
}
public static JObject generateReportPDFRequest(string reportid)
{
try
{
// create the object
JObject jsonRequest = new JObject();
// add version property
jsonRequest.Add("version", "1.0");
// add content object
JObject content = new JObject();
JObject repid = new JObject();
content.Add("customer-report-id", @"" + reportid + @"");
content.Add("content-type", "application/pdf");
JObject reportRequest = new JObject();
jsonRequest.Add("content", content);
return jsonRequest;
}
catch (Exception e)
{
string mess = e.Message;
}
return null;
}
我正在尝试使用Encoding.ASCII.GetBytes(result(过程获取PDF,该过程与WebClient上传字符串帖子一起返回。 流将转换为字节数组并保存到数据库中。 但是该文件是空的。
我有一个人告诉我,我将文件保存为1.6版,下载的是1.4版。 如果这是问题所在,我该如何定义 PDF 版本? 如果没有,如何正确获取这些 PDF 文件?
如果不希望返回字符串,请不要使用UploadString
。有一个适当的重载UploadData
,它返回一个 byte[] 数组。这可以防止任何编码/解码事故的风险。
按如下方式调整代码:
using (var client = new WebClient())
{
client.BaseAddress = add;
client.Headers[HttpRequestHeader.ContentType] = "application/pdf";
client.Headers.Add(HttpRequestHeader.Authorization, "Basic ");
JObject jobject = generateReportPDFRequest(report.ReportID);
byte[] result = client.UploadData(
add,
"POST",
Encoding.UTF8.GetBytes(jobject.ToString()));
retval = AddReportPDF(reportid, result);
}