检查Youtube ID是否对ColdFusion有效

时间:2016-12-21 08:39:34

标签: if-statement youtube coldfusion

我想检查YouTube链接/ ID是否有效。它应该通过if / else语句给我一个答案。

我试过了:

<cfset variables.key = "my_key_value_here">
<cfset variables.headers = "https://www.youtube.com/oembed?format=json&url=http://www.youtube.com/watch?v=#variables.key#">

<cfif (IsArray(#variables.headers#) ? ReMatch('(http:\/\/)(?:www\.)?youtu(?:be\.com\/(?:watch\?|user\/|v\/|embed\/)\S+|\.be\/\S+)',#variables.headers#) : false)>
     Correct Id!
<cfelse>
   There is no video with that Id!
</cfif>

示例中的ID是正确的,应该输出:“正确的ID!”但它始终显示else语句。

感谢您的帮助!

2 个答案:

答案 0 :(得分:5)

我认为通过youtube数据API检查来验证youtube videoId的最佳方式。以下是验证视频时需要遵循的步骤。

  1. 登录您的Google帐户
  2. 转到Google API console
  3. 在Api库中点击YouTube Data API
  4. 创建项目
  5. 为同一个项目创建凭据(这将为您提供API密钥)
  6. 启用API
  7. 完成上述步骤后,您只需使用CFHTTP代码在ColdFusion中实现此API。

    这是一个可以帮助您的代码段。

    <cfset variables.youtubeId = "EUcaCKWk83Q" />
    <cfset variables.youTubeApiKey = "YOUR_API_KEY" />
    <cfhttp url="https://www.googleapis.com/youtube/v3/videos?part=id&id=#youtubeId#&key=#youTubeApiKey#" >
    <cfset response = deserializeJSON(cfhttp.fileContent) />
    <cfif response.pageInfo.totalResults>
        Correct Id!
    <cfelse>
        There is no video with that Id!
    </cfif>
    

答案 1 :(得分:5)

简单的解决方案:

<cfset variables.key = "my_key_value_here">
<cfhttp method="Get" url="https://www.youtube.com/oembed?format=json&url=http://www.youtube.com/watch?v=#variables.key#">
<cfif cfhttp.statusCode EQ "200 OK">
    Correct Id!
<cfelse>
    There is no video with that Id!
</cfif>

<cfoutput>#cfhttp.statusCode#</cfoutput>

我不需要RegEx,因为它总是相同的链接,只是另一个ID。

相关问题