简体   繁体   中英

Using WebRequest(C#) to send data and file

I want to send data and a file using WebRequest.

byte[] fileStream = File.ReadAllBytes(path);

ServicePointManager.ServerCertificateValidationCallback = new RemoteCertificateValidationCallback(delegate { return true; });

WebRequest request = WebRequest.Create(url);

request.ContentType = "application/json";
request.Method = "POST";
request.Credentials = new NetworkCredential("name", "pw");

Stream dataStream = request.GetRequestStream();
dataStream.Write(Encoding.UTF8.GetBytes(data), 0, Encoding.UTF8.GetBytes(data).Length);
//dataStream.Write(fileStream, 0, fileStream.Length);

dataStream.Write(fileStream, 0, fileStream.Length); //CAUSES A CRASH
dataStream.Close();
WebResponse response = request.GetResponse();

I don't know why it fails, if I include the "dataStream.Write(fileStream, 0, fileStream.Length);" line the server fails to accept my stream, saying there was an internal error. I have an working CURL command showing me the data the Server wants.

curl -k -X POST -u name:pw -H "Content-type: application/json"
-H 'Accept:application/json''url'
-d'{parameters}'
--data-binary @file.wav

In case I exclude the mentioned line, the command works as expected, telling me that there was no input file. So I think there might be something wrong about the file.wav

That code will write some JSON-formatted data, immediately followed by the raw bytes of file.wav. That is most likely not what the receiving server is expecting. Typically if you want to send a file and data at the same time you would use a MIME multipart encoding. It is possible that curl is doing that for you automatically. It would be good to confirm that hypothesis by hooking up a debugging proxy such as Fiddler, and watching what curl is actually sending. Then try to emulate that in C#.

If you do need to send a multipart messages, then it would be helpful to know which version of the .NET framework you are using. There are easier ways to do it in some of the newer versions.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM