ColdFusion CFHTTP analogous to CURL

* This is a continuously updated post on the corresponding CFHTTP syntax for CURL. If you need help, send me a message and I will try to help.

I have been trying to integrate different APIs with ColdFusion/Railo recently and the difficult part is of course to understand the way the API is expecting data. Mostly they 3rd party will provide library or code for PHP and .NET, but not for ColdFusion. In some cases they provide the CURL syntax. I thought I will scribble my findings here so that it is useful for someone to write CFHTTP by seeing the CURL syntax.


File Upload 
e.g.: 
  1. to post a file to the folder /upload to the server. The URL is http://app.prasanthkumars.com/upload
  2. the API uses Basic Authorization
  3. File name is test.png

CURL
curl -f file=@test.png "http://username:password@app.prasanthkumars.com/upload"

CFHTTP
<cfset credentials = tobase64("#username#:#password#")>

<cfhttp method="POST" url="http://app.prasanthkumars.com/upload" result="upload_result">
     <cfhttpparam type="header" name="Authorization" value="Basic #credentials#"/>
     <cfhttpparam file="c:\test.png" type="file" name="file" mimetype="image/png">
</cfhttp>


Comments

Chris said…
Hello! Came across this in a Google search. How would you translate this into CFHTTP?

curl -X POST "https://api.getgo.com/oauth/v2/token" \
-H "Authorization: Basic {Base64 Encoded consumerKey and consumerSecret}" \
-H "Accept:application/json" \
-H "Content-Type: application/x-www-form-urlencoded" \
-d "grant_type=refresh_token&refresh_token={refresh_token}"
Hi Chris,
You can try this code and see the output.

<cfset credentials = tobase64("#consumerKey#:#consumerSecret#")>

<cfhttp method="POST" url="https://api.getgo.com/oauth/v2/token" result="upload_result">
<cfhttpparam type="header" name="Authorization" value="Basic #credentials#"/>
<cfhttpparam type="header" name="Accept" value="application/json"/>
<cfhttpparam type="header" name="Content-Type" value="application/x-www-form-urlencoded"/>
<cfhttpparam type="body" value="grant_type=refresh_token&refresh_token={refresh_token}">


I can see that you are trying to consume an OAuth API. So, it is better to use an OAuth library available for CF like http://oauth.riaforge.org/
sulman said…
Hi,

What will be these two lines in cfhttp?

curl_setopt($cURLConnection, CURLOPT_REFERER, 'http://127.0.0.1:53121');
curl_setopt($cURLConnection, CURLOPT_RETURNTRANSFER, true);

Thanks!

Popular posts from this blog

Hide notification content in Android lock screen for Messages, email, whatsapp and selected apps.

Array functions in JavaScript