【问题标题】:How can I make a local file as body of an HttpWebRequest? [duplicate]如何将本地文件作为 HttpWebRequest 的主体? [复制]
【发布时间】:2015-04-12 03:13:34
【问题描述】:

例如:

我要根据这个reference发布数据 他们要求以本地文件为主体发布请求。

他们建议的卷曲是:curl -i --data-binary @test.mp3 http://developer.doreso.com/api/v1

但是我怎样才能在 c# 中做同样的事情呢?

【问题讨论】:

    标签: c# post curl httpwebrequest webrequest


    【解决方案1】:

    尝试使用HttpWebRequest 类并在multipart/form-data 请求中发送文件。

    这是一个示例代码,您可以在进行一些修改后使用。

    先读取文件内容:

    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;
    

    将文件作为正文请求发送:

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

    如果需要,请使用响应:

    Console.WriteLine(result);
    

    【讨论】:

    • 不要commit plagiarism,尤其是当该代码不起作用时(是的,我看到你忍者 - 编辑相似之处)。您也不想一次读取字节数组中的整个文件。
    • 快速浏览一下文档说 Content-Type 应该是“application/octet-stream”,而不是“multipart/form-data”
    • 谢谢@ry8806,我已经编辑了我的答案。
    猜你喜欢
    • 2018-07-18
    • 1970-01-01
    • 2013-01-07
    • 1970-01-01
    • 1970-01-01
    • 2018-09-27
    • 1970-01-01
    • 1970-01-01
    • 2011-01-23
    相关资源
    最近更新 更多