在C#卷曲通话,旗(cURL call in C# with flag)

2019-07-31 13:17发布

我想提出在C#中的以下卷曲电话:

curl "http://localhost:8983/solr/update/extract?literal.id=doc1&commit=true" -F "myfile=@tutorial.html"

我发现,我应该使用WebRequest类,但我仍然不知道如何处理这部分:

-F "myfile=@tutorial.html"

Answer 1:

从代码段http://msdn.microsoft.com/en-us/library/debx8sh9.aspx展示了如何使用WebRequest类发送POST数据:

// Create a request using a URL that can receive a post. 
WebRequest request = WebRequest.Create("http://localhost:8983/solr/update/extract?literal.id=doc1&commit=true");
// Set the Method property of the request to POST.
request.Method = "POST";
// Create POST data and convert it to a byte array.
string postData = "myfile=@tutorial.html";
byte[] byteArray = Encoding.UTF8.GetBytes(postData);
// Set the ContentType property of the WebRequest.
request.ContentType = "application/x-www-form-urlencoded";
// Set the ContentLength property of the WebRequest.
request.ContentLength = byteArray.Length;


Answer 2:

作为一种替代的WebRequest,您可以考虑使用WebClient类。 它提供了可能被认为比的WebRequest一个更清洁,更简单的语法。 事情是这样的:

using (WebClient client = new WebClient())
        {
            client.Headers[HttpRequestHeader.ContentType] = "application/x-www-form-urlencoded";

            byte[] postResult = client.UploadFile("http://localhost:8983/solr/update/extract?literal.id=doc1&commit=true", "POST", "tutorial.html");
        }

见http://msdn.microsoft.com/en-us/library/esst63h0%28v=vs.100%29.aspx



文章来源: cURL call in C# with flag
标签: c# .net curl solr