c# - 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
开始接收良好的数据并突然停止:/
解决方案
推荐阅读
- twitter-bootstrap - Bootstrap 4:如何使用 SCSS 构建灵活的容器宽度,例如 container-sm-10
- asp.net-core - .Net Core 如何在应用程序中的任何位置访问配置
- java - 错误:java:找不到模块:javafx.application
- android - 在 WebView 中截取页面呈现的最佳点?
- kubernetes - Kubernetes ExternalName 服务在 DNS 中不可见
- php - 将原始查询添加到雄辩的关系
- performance - 为什么修改指令会在 x86 上导致巨大的 i-cache 和 i-TLB 未命中?
- svg - SVG 在网页上工作,但不是作为嵌入式 .svg 文件
- java - 该项目未构建,因为它的构建路径不完整 - Eclipse Oxygen
- java - java - 如何在java中复制数组值而不是引用?