Webclient equivalent of CURL command

孤人 提交于 2021-02-10 14:19:23

问题


I am trying to upload a file via a POST to a REST API in a c# winform.

If I run the following command with curl the file is uploaded successfully:

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:

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.

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

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?


回答1:


How can I simulate the CURL command above from my app?

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


来源:https://stackoverflow.com/questions/28769645/webclient-equivalent-of-curl-command

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!