如何将本地文件作为HttpWebRequest的主体? [英] How can I make a local file as body of an HttpWebRequest?

查看:145
本文介绍了如何将本地文件作为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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆