0

接收和发送带有签名的 pdf 文件的 Web 应用程序。我将 httpwebrequest 中的 pdf 文件发送到应用程序。但没有收到带有 httpwebresponse 的 pdf 文件?

我的代码

byte[] pdfFile = File.ReadAllBytes("c:\\sample.pdf");

WebRequest request = WebRequest.Create("URL");
request.Credentials = new NetworkCredential("Username", "Password");
request.Proxy.Credentials = new NetworkCredential("Username", "Password");
request.Method = "POST";
request.ContentLength = pdfFile.Length;
request.ContentType = "application/pdf";

Stream stream = request.GetRequestStream();
stream.Write(pdfFile, 0, pdfFile.Length);
stream.Close();


WebResponse resp = request.GetResponse();
var buffer = new byte[4096];
MemoryStream memoryStream = new MemoryStream();
Stream responseStream =resp.GetResponseStream();

{
    int count;
    do
    {
        count = responseStream.Read(buffer, 0, buffer.Length);
         memoryStream.Write
    (buffer, 0, responseStream.Read(buffer, 0,  buffer.Length));
    } while (count != 0);
}
resp.Close();
byte[] memoryBuffer = memoryStream.ToArray();
System.IO.File.WriteAllBytes(@"c:\sample1.txt", memoryBuffer);
int s = memoryBuffer.Length;

BinaryWriter binaryWriter = 
new BinaryWriter(File.Open(@"c:\sample2.txt", FileMode.Create));
binaryWriter.Write(memoryBuffer);
binaryWriter.Close();


//Read Fully is :

public static byte[] ReadFully(Stream input)
{
    using (MemoryStream ms = new MemoryStream())
    {
        input.CopyTo(ms);
        return ms.ToArray();
    }
}
4

1 回答 1

1

您在阅读中遇到的一个问题是:

int count;
do
{
    count = responseStream.Read(buffer, 0, buffer.Length);
    memoryStream.Write(buffer, 0, responseStream.Read(buffer, 0,  buffer.Length));
} while (count != 0);

您每次通过循环读取缓冲区两次。您第一次读取的字节会丢失,因为您覆盖了它们。您的代码应该是:

int count;
do
{
    count = responseStream.Read(buffer, 0, buffer.Length);
    memoryStream.Write(buffer, 0, count);
} while (count != 0);

另外:我不明白您为什么要将 PDF 写入请求流。您是否尝试将 PDF 发送到服务器并让它发回相同的文件?

你到底想在这里做什么?

于 2013-08-26T13:37:53.877 回答