c# - 将 Curl 脚本转换为 C#

标签 c# curl

我有一个下载文件的 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 Web客户端 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/

相关文章:

PHP异步多文件读写

php - 停止 PHP Curl 下载

curl - 如何使用curl命令行通过HTTP基本身份验证访问网页

c# - 跨进程测量时间

c# - 如何将这两个 linq 查询组合成一个查询?

c# - 在控制台应用程序中缓存

c# - 从服务器生成的元数据是否可从爬虫和机器人读取?

php - 如何获取 cURL 获取的最后一个 URL?

c# - COM 互操作、C#、Visual Studio 2010 -> 嵌入互操作类型

php - cURL cookie 值