使用c#在HttpWebRequest中添加预告片

时间:2013-09-24 11:17:36

标签: c# node.js httpwebrequest transfer-encoding

我正在尝试在HttpWebRequest标头中添加预告片,但在文件数据结束后它不会附加预告片。

wreq.ContentType = "application/octet-stream";
wreq.AllowWriteStreamBuffering = false;
wreq.SendChunked = true;
//wreq.Headers.Add(HttpRequestHeader.Te, "trailers");
wreq.Headers.Add(HttpRequestHeader.Trailer, "Test");
wreq.Headers["Test"] = "the-value";

using (Stream POSTstream = wreq.GetRequestStream())
{
      //dataByte is file-data in byte[]
      POSTstream.Write(dataByte, 0, dataByte.Length); 
      POSTstream.Flush();
      //hashValue is trailer in byte[]
      POSTstream.Write(hashValue, 0, hashValue.Length);
      POSTstream.Flush();
      POSTstream.Close();
}

它应该在空白块之后追加这个预告片“Test”@ EOF,但它不会附加它。当我试图以编程方式添加预告片时,它将其视为文件数据而不是预告片。

预期请求:

POST <URL> HTTP/1.1
Content-Type: application/octet-stream
Trailer: Test
Transfer-Encoding: chunked

5d    
File-data

0
Test: the-value

实际要求:

POST <URL> HTTP/1.1
Content-Type: application/octet-stream
Trailer: Test
Transfer-Encoding: chunked

5d    
File-data

5A
Test: the-value
0

为什么这个测试预告片没有得到空白块。此预告片将在服务器上用于识别文件结尾。 请帮助。

1 个答案:

答案 0 :(得分:2)

经过一周多的研究,我发现Dotnet不允许在httprequest中添加预告片。为了达到上述预期的要求,我使用了Node.js.为此,

首先,我创建了app.js文件,其中包含使用预告片创建请求并从服务器获取响应的代码:

var http = require('http');
var fs = require('fs');
var options = {hostname: 'ABC',port: 6688,path: 'XYZ/101/-3/test.file',method: 'POST',
headers: {'Content-type' : 'application/octet-stream','Trailer' : 'Test','Transfer-Encoding': 'chunked'}};
var fileContent =  fs.readFileSync('C:\\test.file');
var req = http.request(options, function(res) {
res.setEncoding('utf8');
res.on('data', function (chunk) {fs.writeFile('C:\\response.xml', chunk);});});
req.on('error', function(e) {fs.writeFile('C:\\response.xml','Error: ' + e.message);});
var len = fileContent.length;
var bufSize = 4096;
for (var i = 0 ; i < len ; ) {
if (i+bufSize <len){req.write(fileContent.slice(i, i+bufSize));}
else{req.write(fileContent.slice(i,len));req.addTrailers({'Test': 'TESTTEST'});req.end();}i = i +bufSize;
}

从dotnet运行这个app.js文件作为应用程序并获得响应:

//build app.js file content
var template = GetAppJSString();
var appjsfile = "C:\\app.js";
using (var sw = new StreamWriter(appjsfile))
{
    sw.Write(template);
    sw.Close();
}

var psi = new ProcessStartInfo
{
    CreateNoWindow = true,
    FileName = "C:\\Node.exe",
    Arguments = "\"" + appjsfile + "\"",
    UseShellExecute = false,
    WindowStyle = ProcessWindowStyle.Hidden
};

try
{
    _nodeProcess.StartInfo = psi;
    _nodeProcess.Start();
    _nodeProcess.WaitForExit();

    //read and process response 
    var responseText = string.Empty;
    using (var sr = new StreamReader("C:\\response.xml"))
        {
            responseText = sr.ReadToEnd();
            sr.Close();
        }
        File.Delete("C:\\response.xml");
    // process response

}
catch (Exception ex) { }

希望这会有助于他人并节省他们的时间。