首页 > 解决方案 > webResponse 响应不完整 pdf

问题描述

我正在发送webRequest并从中获取 PDF 响应,但我得到的响应不完整。好像webResponse只给我几行PDF。当我在“邮递员”中提出相同的请求时,我收到了近 900 行响应,但webRequest在我的代码中我只收到了几行。看起来响应突然停止并“杀死”数据传输,并且没有收到完整的 pdf。当我打开文件时,它是空白的 pdf,里面没有数据。这是我的代码:

[HttpGet]
public FileContentResult GenerateBarcodePDF(string barcode)
{
    var partner = _settingService.GetSetting("venisettings.username")?.Value;
    var bytes = GetBarcode(barcode,partner);
    var labelName = barcode + ".pdf";
    var file = File(bytes, "application/pdf", labelName);

    return file;
}
public byte[] GetBarcode(string barcode, string partner)
{
    byte[] content = new byte[64];
    WebRequest quotesrequest = WebRequest.Create("https://someurlineed");
    string data = "user=myusername&pass=mypass&pack_no[]=" + barcode + "&type=a4";
    byte[] dataStream = Encoding.UTF8.GetBytes(data);
    quotesrequest.Method = "POST";
    quotesrequest.ContentType = "application/x-www-form-urlencoded";
    Stream newStream = quotesrequest.GetRequestStream();
    newStream.Write(dataStream, 0, dataStream.Length); // Send the data.
    newStream.Close();

    Response.Headers.Add("Content-Disposition", "attachment; filename=\"label.pdf\"");
    Response.Headers.Add("Content-Transfer-Encoding", "binary");
    Response.Headers.Add("Content-Type", "application/pdf");
    Response.Headers.Add("Keep-Alive", "timeout=5, max=300");
    Response.Headers.Add("Connection", "Keep-Alive");

    WebResponse webResponse = quotesrequest.GetResponse();
    Stream stream = webResponse.GetResponseStream();
    StreamReader streamreader = new StreamReader(stream);
    string responseFromServer = streamreader.ReadToEnd();

    var plainTextBytes = Encoding.UTF8.GetBytes(responseFromServer);
    var bytesINee = Convert.ToBase64String(plainTextBytes);

    if (!string.IsNullOrWhiteSpace(responseFromServer))
    {
        content = Convert.FromBase64String(bytesINee);
        return content;
        throw new Exception("something bad happened");
    }
    return content;
}

最后我得到空白的PDF文件,里面什么都没有。这是我在“邮递员”中得到的响应时间:

邮递员回应

这就是我在“webResponse”中的内容:

网络响应

也许有人可以告诉我,我错过了什么?为什么它看起来weResponse开始接收良好的数据并突然停止:/

标签: c#asp.netpdfhttpwebrequesthttpwebresponse

解决方案


推荐阅读