phpcurlcoldfusioncfhttp

curl to cfhttp translation


I am trying to translate a PHP script into ColdFusion and did not succeed. Could somebody help me?

Original PHP script (for unifi wlan manager api):

$unifiServer = "https://xxx.xxx.xxx.xxx:xxxx";
$unifiUser = "xxxxx";
$unifiPass = "xxxxx";

// Start Curl for login
$ch = curl_init();
// We are posting data
curl_setopt($ch, CURLOPT_POST, TRUE);
// Set up cookies
$cookie_file = "/tmp/unifi_cookie";
curl_setopt($ch, CURLOPT_COOKIEJAR, $cookie_file);
curl_setopt($ch, CURLOPT_COOKIEFILE, $cookie_file);
// Allow Self Signed Certs
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, FALSE);
// Force SSL1 only
curl_setopt($ch, CURLOPT_SSLVERSION, 1);
// Login to the UniFi controller
curl_setopt($ch, CURLOPT_URL, "$unifiServer/api/login");
$data = json_encode(array("username" => $unifiUser,"password" => $unifiPass));
curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-Type: application/json'));
// send login command
curl_exec ($ch);

ColdFusion cfhttp translation:

<cfhttp url="https://xxx.xxx.xxx.xxx:8443/api/login" method="POST" result="test">
    <cfhttpparam type = "formField" name = "username" value="xxxxxxx">
    <cfhttpparam type = "formField" name = "password" value="xxxxxxxx">
    <cfhttpparam type="header" name="Content-Type" value="application/json">    
</cfhttp>

<cfdump var="#test#">

cfhttp fails with:

"HTTP/1.1 400 Bad Request Server"
msg" : "api.err.Invalid" , "rc"

SSL certificate is installed in cert store.


Solution

  • $unifiUser = "xxxxx";
    $unifiPass = "xxxxx";
    $data      = json_encode(array("username" => $unifiUser,"password" => $unifiPass));
    

    translates to

    <cfset unifiUser = "xxxxx">
    <cfset unifiPass = "xxxxx">
    <cfset data      = serializeJSON({ "username" = unifiUser, "password" = unifiPass })>
    

    and your curl's payload translates to

    <cfhttp url="https://xxx.xxx.xxx.xxx:8443/api/login" method="POST" result="test">
        <cfhttpparam type="body" value="#data#">
        <cfhttpparam type="header" name="Content-Type" value="application/json">
    </cfhttp>
    
    <cfdump var="#test#">
    

    To send a cookie:

    <cfset cookie_file    = "/tmp/unifi_cookie">
    <cfset cookie_content = fileRead(cookie_file)>
    

    and add

    <cfhttpparam type="header" name="Cookie" value="#cookie_content#">
    

    If you need to send multiple cookies, you have to concatenate them in cookie_content using semicolon ;.