How can I make a local file as body of an HttpWebRequest? [duplicate]

∥☆過路亽.° 提交于 2019-12-12 01:53:02

问题


For example:

I have to post data according to this reference They ask to post a request with a local file as the body.

The curl they suggest is: curl -i --data-binary @test.mp3 http://developer.doreso.com/api/v1

But how can I do the same in c#?


回答1:


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.

First read the contents of the file:

byte[] fileToSend = File.ReadAllBytes(@"C:\test.mp3"); 

Then prepare the HttpWebRequest object:

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();
}

Read the response then:

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);


来源:https://stackoverflow.com/questions/28459609/how-can-i-make-a-local-file-as-body-of-an-httpwebrequest

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!