我正在尝试在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
为什么此测试预告片不能追随空白块。该预告片将在服务器上用于标识文件结尾。
请帮忙。
最佳答案
经过一个多星期的研究,我发现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) { }
希望这会帮助其他人并节省他们的时间。
关于c# - 使用C#在HttpWebRequest中添加预告片,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/18980153/