WebClient等效于CURL命令 [英] Webclient equivalent of CURL command

查看:41
本文介绍了WebClient等效于CURL命令的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试通过POST将文件上传到c#winform中的REST API.

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

如果我对curl执行以下命令,则文件上传成功:

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

我尝试在WinForm中使用WebClient:

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

但是我只得到一台(500)内部服务器.

But I just get a (500) Internal Server.

使用小提琴手检查此内容,并在CURL中添加以下标头:

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

但是检查我的WebClient方法会显示以下内容:

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

如何从我的应用程序模拟上面的CURL命令?

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

推荐答案

如何从我的应用程序模拟上面的CURL命令?

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

使用 HttpWebRequest .它为您提供了更大的灵活性.如下:

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

这篇关于WebClient等效于CURL命令的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆