Sunday, August 26, 2012

Different ways of sending HTTP API requests (PHP/Curl/Wget)

I was recently debugging an API request in our application and I had to try using different tools to send an HTTP request to see what's the cause of the problem. It's funny how some API's look very complicated at first (hmmm SOAP anyone?) but in essence it is just an HTTP request with a specific format. Let's look how I connect to the Plesk RPC API using curl on PHP, and also curl and wget on the shell/command line:

What this does is:
- Post XML content to a specific URL
- Set headers (for login values, content type, etc)
- Disable SSL certification check (useful for development)

Curl on PHP:
$curl = curl_init();
curl_setopt($curl, CURLOPT_URL, '');
curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
curl_setopt($curl, CURLOPT_POST,           true);
curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, false);
curl_setopt($curl, CURLOPT_HTTPHEADER, array(
"HTTP_AUTH_LOGIN: my_username",
"HTTP_AUTH_PASSWD: my_password",
"Content-Type: text/xml"));
curl_setopt($curl, CURLOPT_POSTFIELDS, "<xmldata>");
$result = curl_exec($curl);

Curl on shell:
curl --insecure -H 'HTTP_AUTH_LOGIN:my_username' -H 'HTTP_AUTH_PASSWD:my_password' -H 'HTTP_PRETTY_PRINT: TRUE' -H 'Content-Type: text/xml' --data '<xmldata>'

Wget on shell:
wget --no-check-certificate --header 'HTTP_AUTH_LOGIN:my_username' --header 'HTTP_AUTH_PASSWD:my_password' --header 'HTTP_PRETTY_PRINT: TRUE' --header 'Content-Type: text/xml' --post-data '<xmldata>'

You can even use PHP's fopen but I wasn't able to try that.

No comments:

Post a Comment