简体   繁体   English

Webclient等效于CURL命令

[英]Webclient equivalent of CURL command

I am trying to upload a file via a POST to a REST API in ac# winform. 我试图通过POST将文件上传到ac#winform中的REST API。

If I run the following command with curl the file is uploaded successfully: 如果我使用curl运行以下命令,则文件上传成功:

curl.exe -H "Content-type: application/octet-stream" -X POST http://myapiurl --data-binary @C:\test.docx

I have tried using WebClient in my WinForm: 我尝试在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;
            } 

But I just get a (500) Internal Server. 但我只得到一个(500)内部服务器。

Checking this with fiddler the following headers are added with CURL: 使用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

But checking my WebClient method shows the following: 但是检查我的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

How can I simulate the CURL command above from my app? 如何从我的应用程序模拟上面的CURL命令?

How can I simulate the CURL command above from my app? 如何从我的应用程序模拟上面的CURL命令?

Use HttpWebRequest . 使用HttpWebRequest It offers you more flexibility. 它为您提供更多灵活性。 As follows: 如下:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM