我正在尝试通过POST将文件上传到c#winform中的REST API。
如果我使用curl运行以下命令,则文件上传成功:
curl.exe -H "Content-type: application/octet-stream" -X POST http://myapiurl --data-binary @C:\test.docx
我尝试在WinForm中使用WebClient:
using (var client = new WebClient())
{
client.Headers.Add("Content-Type", "application/octet-stream");
byte[] result = client.UploadFile(url, file);
string responseAsString = Encoding.Default.GetString(result);
tb_result.Text += responseAsString;
}
但我只得到(500)内部服务器。
使用fiddler进行检查时,会在CURL中添加以下标题:
POST http://myapiurl HTTP/1.1
User-Agent: curl/7.33.0
Host: 10.52.130.121:90
Accept: */*
Connection: Keep-Alive
Content-type: application/octet-stream
Content-Length: 13343
Expect: 100-continue
但是检查我的WebClient方法会显示以下内容:
POST http://myapiurl HTTP/1.1
Accept: */*
Content-Type: multipart/form-data; boundary=---------------------8d220bbd95f8b18
Host: 10.52.130.121:90
Content-Length: 13536
Expect: 100-continue
Connection: Keep-Alive
如何从我的应用程序模拟上面的CURL命令?
答案 0 :(得分:0)
如何从我的应用程序模拟上面的CURL命令?
使用HttpWebRequest
。它为您提供更多灵活性。如下:
HttpWebRequest request = (HttpWebRequest)WebRequest.Create("http://myapiurl");
request.Method = "POST";
request.UserAgent = "curl/7.33.0";
request.Host = "10.52.130.121:90";
request.Accept = "Accept=*/*";
request.Connection = "Keep-Alive";
request.ContentType = "application/octet-stream";
request.ContentLength = 13343;
request.Expect = "100-continue";