Amexy
Amexy

Reputation: 21

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

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

Upvotes: 2

Views: 3059

Answers (1)

EZI
EZI

Reputation: 15354

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

Upvotes: 3

Related Questions