Reputation: 1013
We have a process which accesses an external API to obtain and download a PDF file. Here is the process:
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;
}
I'm trying to get the PDF with the Encoding.ASCII.GetBytes(result) process which is return with the WebClient upload string post. The stream is converted to a byte array and saved into the database. But the file is empty.
I had one person tell me that I am saving the file as version 1.6 and what is downloaded is version 1.4. If that is the problem, how do I define the PDF version? If not, how do I get these PDF files properly?
Upvotes: 2
Views: 2202
Reputation: 42414
Don't use UploadString
if you don't want a string to be returned. There is a proper overload UploadData
that returns you an byte[] array. That prevents the risk of any encoding/decoding mishaps.
adapt your code as follows:
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);
}
Upvotes: 1