如何在C#中发送/接收cURL / API请求

时间:2015-07-22 08:22:39

标签: c# api curl webrequest

我的c#programm问题是向在线电话系统发送或接收cURL请求,我希望在那里得到一些帮助:)

我想发送这样的命令:

select t1.* from table1 as t1
inner join
(select distinct Parent_ID from table1 order by Parent_ID limit 3) as t2
on t1.Parent_ID = t2.Parent_ID

服务器以XML格式发回

<add name="analytics" connectionString="mongodb://localhost:27017/kbs_analytics" />
<add name="tracking.live" connectionString="mongodb://localhost:27017/kbs_tracking_live" />
<add name="tracking.history" connectionString="mongodb://localhost:27017/kbs_tracking_history" />
<add name="tracking.contact" connectionString="mongodb://localhost:27017/kbs_tracking_contact" />

我尝试使用WebRequest Class(msdn),但我没有联系。

“System.dll中的System.Net.WebException错误”与服务器的连接失败

curl https://api.placetel.de/api/test \
    -d 'api_key=XXXXXX-XXXX-XXXX-XXXX-XXXXXXXXXXXXXXXXXXXXXXXXXXXX-XXXX-XXXX-XXXX-XXXXXXXXXXX'

来自电话在线系统提供商的API documentation,但仅限德语。

问候

1 个答案:

答案 0 :(得分:3)

我更喜欢使用 WebClient

WebClient wc = new WebClient();
var buf = wc.UploadValues("https://api.placetel.de/api/test", 
                           new NameValueCollection() { { "api_key", "XXXX" } });
var xml = Encoding.UTF8.GetString(buf);

HttpClient

HttpClient client = new HttpClient();
var content = new FormUrlEncodedContent(new Dictionary<string, string>() { 
        { "api_key", "XXXX" } 
});
var resp =  await client.PostAsync("https://api.placetel.de/api/test",content);
var xml = await resp.Content.ReadAsStringAsync();

哪种方法更易于使用。

BTW,-d (or --data) curl 的参数,它不会发送到服务器

PS:您可能还想阅读有关ContentType http://www.freeformatter.com/mime-types-list.html

的内容