将CURL转换为c#
本文关键字:转换 CURL | 更新日期: 2023-09-27 18:18:03
我花了很长时间尝试各种不同的方法将这个curl转换为c#。有人能帮帮我吗?我试图做一个http帖子,并不断得到错误500。下面是我要转换的内容:
curl --user username:password -X POST -d "browser=Win7x64-C1|Chrome32|1024x768&url=http://www.google.com" http://crossbrowsertesting.com/api/v3/livetests/
,这是我现在写的:
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(baseurl);
request.Method = "POST";
request.Accept = "application/json";
request.Credentials = new NetworkCredential(username, password);
var response = request.GetResponse();
string text;
using (var sr = new StreamReader(response.GetResponseStream()))
{
text = sr.ReadToEnd();
values.Add(text);
}
也试过这个方法,但是没有成功:
List<string> data = new List<string>();
data.Add("browser=Win7x64-C1|Chrome20|1024x768");
data.Add("url=URL");
data.Add("format=json");
data.Add("callback=doit");
var request = WebRequest.Create("CrossBrowserTestingURL");
request.Method = "POST";
request.ContentType = "application/x-www-form-urlencoded";
request.Credentials = new NetworkCredential(username, password);
using (var writer = new StreamWriter(request.GetRequestStream()))
{
writer.Write("data=" + data);
}
var response = request.GetResponse();
string text;
using (var sr = new StreamReader(response.GetResponseStream()))
{
text = sr.ReadToEnd();
values.Add(text);
}
我修改了第一个,按照http://msdn.microsoft.com/en-us/library/debx8sh9(v=vs.110).aspx将数据写入请求流,这样做:
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(baseurl);
request.Method = "POST";
request.Accept = "application/json";
request.Credentials = new NetworkCredential(username, password);
request.UserAgent = "curl/7.37.0";
request.ContentType = "application/x-www-form-urlencoded";
using (var streamWriter = new StreamWriter(request.GetRequestStream()))
{
string data = "browser=Win7x64-C1|Chrome32|1024x768&url=http://www.google.com";
streamWriter.Write(data);
}
var response = request.GetResponse();
string text;
using (var sr = new StreamReader(response.GetResponseStream()))
{
text = sr.ReadToEnd();
values.Add(text);
}
刚刚实现了一个实验性的ASP。使用Roslyn
将curl命令转换为c#代码的NET Core应用程序请试一试:
https://curl.olsh.me/
您可以将您的命令粘贴到curlconverter.com/csharp/,它将使用HttpClient
将其转换为以下代码:
using System.Net.Http.Headers;
HttpClient client = new HttpClient();
HttpRequestMessage request = new HttpRequestMessage(HttpMethod.Post, "http://crossbrowsertesting.com/api/v3/livetests/");
request.Headers.Add("Authorization", "Basic " + Convert.ToBase64String(System.Text.ASCIIEncoding.ASCII.GetBytes("username:password")));
request.Content = new StringContent("browser=Win7x64-C1|Chrome32|1024x768&url=http://www.google.com");
request.Content.Headers.ContentType = new MediaTypeHeaderValue("application/x-www-form-urlencoded");
HttpResponseMessage response = await client.SendAsync(request);
response.EnsureSuccessStatusCode();
string responseBody = await response.Content.ReadAsStringAsync();