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

How to send / receive cURL/API requests in C#

我的 c# 程序在向在线电话系统发送或接收 cURL 请求时遇到问题,我希望能得到一些帮助:)

我想发送这样的命令:

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

服务器发回XML

<?xml version="1.0" encoding="UTF-8"?>
<hash>
  <result>1</result>
  <result-code>success</result-code>
  <descr>test login successful v1.1</descr>
</hash>

我尝试使用 WebRequest Class (msdn),但我没有连接。

"Error System.Net.WebException in System.dll" 连接服务器失败

WebRequest request = WebRequest.Create("https://api.placetel.de/");           
            request.Method = "POST";           
            string postData = "-d 'api_key=XXXXXX-XXXX-XXXX-XXXX-XXXXXXXXXXXXXXXXXXXXXXXXXXXX-XXXX-XXXX-XXXX-XXXXXXXXXXX'";
            byte[] byteArray = Encoding.UTF8.GetBytes(postData);
            request.ContentType = "/api/test.xml";

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

问候

我更喜欢使用 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();

哪些方法更容易使用。

顺便说一句,-d (or --data)curl的一个参数,不会发送到服务器

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

的内容