如何在 C# 中发送/接收 cURL/API 请求 [英] How to send / receive cURL/API requests in C#

查看:67
本文介绍了如何在 C# 中发送/接收 cURL/API 请求的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

i have problems with my c# programm to send or receive cURL requests to a online telephone system, i hope to get some help there :)

我想发送这样的命令:

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

服务器以 XML 格式返回

the server send in XML back

<?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 类 (msdn) 但我没有连接.

i have try with the WebRequest Class (msdn) but i don´t get a connection.

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

"Error System.Net.WebException in System.dll" Connection to server failed

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 文档,但仅限于德语.

there is a API documentation from the telephone online system provider ,but only in german.

问候

推荐答案

我更喜欢使用 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(或--data)curl的参数,不会发送到服务器

BTW, -d (or --data) is a parameter of curl, it is not sent to server

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

这篇关于如何在 C# 中发送/接收 cURL/API 请求的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆