C#正在将文件上载到HTTPServer
本文关键字:上载 HTTPServer 文件 | 更新日期: 2023-09-27 18:29:25
我需要编写一个http客户端来使用http将一个巨大的文件上传到服务器。代码
public Stream function()
{
string postData = "This is a test that posts this string to a Web server.";
byte[] byteArray = Encoding.UTF8.GetBytes (postData);
// Set the ContentType property of the WebRequest.
request.ContentType = "application/x-www-form-urlencoded";
// Set the ContentLength property of the WebRequest.
request.ContentLength = byteArray.Length;
request.Method = "POST";
// Get the request stream.
Stream dataStream = request.GetRequestStream ();
// Write the data to the request stream.
return dataStream;
}
然后,我将dataStream返回给该函数的调用方,以便应用程序继续使用write写入流。然后,一旦完成写入,就会调用GetResponse,然后关闭流。但我得到了异常
协议违反异常写入流时位于System.Net.HttpWriteStream.Write()。
请帮忙。
在使用浏览器时,您是否考虑过使用Fiddler来调试流程
这是一个简单的代理,允许您检查http流量。
ProtocolViolationException
可能是因为请求方法是GET或HEAD而抛出的。
您必须将方法设置为POST,如下所示:
// Set the 'Method' property of the 'Webrequest' to 'POST'.
request.Method = "POST";
请参阅MSDN上的HttpWebRequest.GetRequestStream方法文档。