我有一个curl脚本下载文件。如何将其转换为C#?

Dim strCurl1
Dim strCurl2
Dim strCurl3
Dim strCurl4

strCurl1 = "c:\temp\Curl\curl -d "
strCurl2 = "username=myUser&password=passwrd&asof=" & fileName & "&format=csv"
strCurl3 = "https://website/PresentValueServlet > " & "c:\temp\Curl\Results_" & fileName & ".csv"
strCurl4 = strCurl1 & Chr(34) & strCurl2 & Chr(34) & " " & strCurl3 & " --insecure  --proxy proxy.myserver.com:8080 --proxy-user admin:passAdmin"

Set objShell = CreateObject("WScript.Shell")
objShell.run "cmd /K " & strCurl4


到目前为止我的C#...

string username = "myUser";
string password = "passwrd";
string fileDestination = @"c:\temp\Curl\Results_" + fileName + ".csv";
using (WebClient client = new WebClient())
{
   client.Credentials = new NetworkCredential(username, password);
   client.DownloadFile(string.Format("https://website/PresentValueServlet"), fileDestination);
}


使用代理更新了C#代码...

WebProxy proxy = new WebProxy("myurl:8080", true);
proxy.Credentials = new NetworkCredential("admin", "pswrd");
client.Proxy = proxy;


错误:远程服务器返回错误:(403)禁止。

最佳答案

使用以下选项之一:

HttpWebRequest / HttpWebResponse
网络客户端
HttpClient(可从.NET 4.5开始)

我强烈建议使用HttpClient类,因为从可用性的角度来看,它比前两个更好。

对于您的情况,您可以这样做:

using System.Net.Http;

var client = new HttpClient();

// Create the HttpContent for the form to be posted.
var requestContent = new FormUrlEncodedContent(new [] {
new KeyValuePair<string,>("text", "This is a block of text"),
});

// Get the response.
HttpResponseMessage response = await client.PostAsync(
"http://api.repustate.com/v2/demokey/score.json",
requestContent);

// Get the response content.
HttpContent responseContent = response.Content;

// Get the stream of the content.
using (var reader = new StreamReader(await responseContent.ReadAsStreamAsync()))
{
// Write the output.
Console.WriteLine(await reader.ReadToEndAsync());
}


这个答案来自this site

我在网络上找到了this解决方案的另一种参考。

您也可以尝试查看this答案。

关于c# - 将Curl脚本转换为C#,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/32501249/

10-09 00:46