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

两盒软妹~` 提交于 2019-12-02 04:44:48

问题


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 :)

I want to send commands like this:

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

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>

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

"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";

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

greetings


回答1:


I prefer using 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);

or 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();

which have methods easier to use.

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

PS: You may also want to read something about ContentType http://www.freeformatter.com/mime-types-list.html



来源:https://stackoverflow.com/questions/31557692/how-to-send-receive-curl-api-requests-in-c-sharp

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!