2017-07-30 72 views
1

我想从我的PHP代码使用curl调用Natural Language Understanding Watson API。我已经成功地尝试从终端卷曲。它详细介绍了执行此命令的一些结果:从PHP代码调用Watson API

curl -u "my_username":"my_password" "https://gateway.watsonplatform.net/natural-language-understanding/api/v1/analyze?version=2017-02-27&text=I%20still%20have%20a%20dream.&features=sentiment,keywords" 

然而,当我尝试使用此代码使用卷曲在PHP中:

<?php 
$url = "https://gateway.watsonplatform.net/natural-language-understanding/api/v1/analyze?version=2017-02-27&text=I%20still%20have%20a%20dream%2C%20a%20dream%20deeply%20rooted%20in%20the%20American%20dream%20%E2%80%93%20one%20day%20this%20nation%20will%20rise%20up%20and%20live%20up%20to%20its%20creed%2C%20%22We%20hold%20these%20truths%20to%20be%20self%20evident%3A%20that%20all%20men%20are%20created%20equal.&features=sentiment,keywords"; 
$post_args = array(
     'version' => '2017-02-27', 
     'url' => 'https://davidwalsh.name/curl-post', 
     'features' => 'sentiment,keywords' 
    ); 
$headers = array(
     'Content-Type:application/json' 
    ); 
$ch = curl_init(); 
curl_setopt($ch, CURLOPT_USERPWD, "my_username:my_password"); 
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); 
//curl_setopt($curl, CURLOPT_HTTPAUTH, CURLAUTH_BASIC); 
//curl_setopt($ch, CURLOPT_POST, true); 
curl_setopt($ch, CURLOPT_URL, $url); 
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers); 
//curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($post_args)); 
$result = curl_exec($ch); 
    if ($result === FALSE) { 
     die('Send Error: ' . curl_error($ch)); 
    } 
curl_close($ch); 
echo $result; 
?> 

我得到这样的结果:

{ 
"error": "unsupported media type", 
"code": 415 
} 

什么都要做完了?

+0

为什么你评论'CURLOPT_POST'和'CURLOPT_HTTPAUTH'选项?此外,你永远不会发送你的POST参数 – BeetleJuice

+0

我试过了你确切的代码,它在我的一端很好 –

+0

问题可能与版本有关。你有没有链接到API文档? –

回答

1

我不敢相信我因为空白而被卡在这里。 更换此:

$headers = array(
     'Content-Type:application/json' 
    ); 

$headers = array(
     'Content-Type: application/json' 
    ); 

工作。请注意0​​和application/json之间的空格。