【问题标题】:curl to cfhttp translationcurl 到 cfhttp 的翻译
【发布时间】:2017-02-22 15:06:41
【问题描述】:

我正在尝试将 PHP 脚本转换为 ColdFusion,但没有成功。有人可以帮我吗?

原始 PHP 脚本(用于 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 翻译:

<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 失败:

“HTTP/1.1 400 错误请求服务器”
msg" : "api.err.Invalid" , "rc"

SSL 证书已安装在证书存储中。

【问题讨论】:

  • 尝试在请求正文中发送 usernamepassword 而不是 formfield,因为数据将是 url 编码的,并且从 php sn-p 看起来你需要它json 编码。

标签: php curl coldfusion cfhttp


【解决方案1】:
$unifiUser = "xxxxx";
$unifiPass = "xxxxx";
$data      = json_encode(array("username" => $unifiUser,"password" => $unifiPass));

翻译成

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

你的 curl 的有效载荷转换为

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

发送 cookie:

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

并添加

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

如果您需要发送多个 cookie,您必须在 cookie_content 中使用分号 ; 连接它们。

【讨论】:

  • 太好了,行得通!非常感谢 Alex 的翻译!
  • 谢谢亚历克斯。我收到 cf 错误“文件或目录 /tmp/unifi_Cookie 不存在”
  • 可能是什么原因?
  • 错误告诉你:cookie文件不存在。您需要描述 cookie/信息的实际来源。您可能需要存储初始请求的响应并将数据用于后续请求。请打开一个新问题并详细描述您的工作流程。
  • 我找到了解决方案。当我使用
【解决方案2】:

如果 CFHTTP 让您头疼(在处理 SSL/HTTPS 时经常出现这种情况),请考虑使用 CFEXECUTE 从命令行调用 CURL。

例如:

<cfexecute timeout="10" name="curl" variable="myVar" arguments="https://google.com"></cfexecute>

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-06-10
    • 1970-01-01
    • 1970-01-01
    • 2017-11-28
    • 1970-01-01
    相关资源
    最近更新 更多