如何将本地文件作为HttpWebRequest的主体? [英] How can I make a local file as body of an HttpWebRequest?
问题描述
例如:
我必须根据此参考发布数据 他们要求发布带有本地文件作为正文的请求.
I have to post data according to this reference They ask to post a request with a local file as the body.
他们建议的卷曲度是:curl -i --data-binary @test.mp3 http://developer.doreso.com/api/v1
The curl they suggest is: curl -i --data-binary @test.mp3 http://developer.doreso.com/api/v1
但是我该如何在c#中做同样的事情?
But how can I do the same in c#?
推荐答案
尝试使用HttpWebRequest
类并在multipart/form-data
请求中发送文件.
Try using HttpWebRequest
class and send file in a multipart/form-data
request.
这里是示例代码,您可以对其进行一些修改.
Here is a sample code that you may use with some modifications.
首先读取文件的内容:
byte[] fileToSend = File.ReadAllBytes(@"C:\test.mp3");
然后准备HttpWebRequest
对象:
string url = "http://developer.doreso.com/api/v1";
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
request.Method = "POST";
request.ContentType = "application/octet-stream";
request.ContentLength = fileToSend.Length;
将文件发送为正文请求:
Send the file as body request:
using (Stream requestStream = request.GetRequestStream())
{
requestStream.Write(fileToSend, 0, fileToSend.Length);
requestStream.Close();
}
然后阅读响应:
HttpWebResponse response = (HttpWebResponse)request.GetResponse();
string result;
using (StreamReader reader = new StreamReader(response.GetResponseStream()))
{
result = reader.ReadToEnd();
}
如果需要,请使用响应:
Use the response if you need:
Console.WriteLine(result);
这篇关于如何将本地文件作为HttpWebRequest的主体?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!