【发布时间】:2016-08-18 10:34:50
【问题描述】:
我需要发布以下请求:
POST http://target-host.com/some/endpoint HTTP/1.1
Content-Type: multipart/form-data; boundary="2e3956ac-de47-4cad-90df-05199a7c1f53"
Accept-Encoding: gzip, deflate
Connection: Keep-Alive
Content-Length: 6971
Host: target-host.com
--2e3956ac-de47-4cad-90df-05199a7c1f53
Content-Disposition: form-data; name="some-label"
value
--2e3956ac-de47-4cad-90df-05199a7c1f53
Content-Disposition: form-data; name="file"; filename="my-filename.txt"
<file contents>
--2e3956ac-de47-4cad-90df-05199a7c1f53--
我可以使用 Python requests 库非常轻松地做到这一点,如下所示:
import requests
with open("some_file", "rb") as f:
byte_string = f.read()
requests.post(
"http://target-host.com/some/endpoint",
data={"some-label": "value"},
files={"file": ("my-filename.txt", byte_string)})
有没有办法对Flurl.Http 库做同样的事情?
我对@987654321@ 的做法的问题是它会为每个键值对插入Content-Type 标头,它会为文件数据插入filename*=utf-8'' 标头。但是,我尝试将请求发布到的服务器不支持这一点。还要注意标题中 name 和 filename 值周围的双引号。
编辑:下面是我使用Flurl.Http 发出帖子请求的代码:
using System.IO;
using Flurl;
using Flurl.Http;
namespace ConsoleApplication
{
public class Program
{
public static void Main(string[] args)
{
var fs = File.OpenRead("some_file");
var response = "http://target-host.com"
.AppendPathSegment("some/endpoint")
.PostMultipartAsync(mp => mp
.AddString("some-label", "value")
.AddFile("file", fs, "my-filename.txt")
).Result;
}
}
}
【问题讨论】:
-
这是一个非常合理的编程问题。投票关闭它的人可以解释一下吗?
-
你是说在文件数据的头部包含
filename*实际上导致调用失败?
标签: c# post multipartform-data flurl