2017-07-30 1 views
1

J'essaie d'appeler Natural API Understanding Watson API à partir de mon code PHP en utilisant curl. J'ai essayé avec succès de boucler du terminal. Il donne un résultat sur l'exécution de cette commande:Appel de l'API Watson à partir du code PHP

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" 

Cependant, lorsque je tente d'utiliser boucle en php en utilisant ce code:

<?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; 
?> 

Je reçois ce résultat:

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

Que devrait être terminé?

+0

Pourquoi commentez-vous les options 'CURLOPT_POST' et' CURLOPT_HTTPAUTH'? En outre, vous n'envoyez jamais vos arguments POST – BeetleJuice

+0

J'ai essayé le code exact que vous avez et c'est bon sur ma fin –

+0

Le problème pourrait être lié à la version. Avez-vous un lien vers la documentation de l'API? –

Répondre

1

Je ne peux pas croire que j'étais coincé ici en raison d'un espace vide. Remplacement ceci:

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

avec

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

travaillé. Notez l'espace vide entre : et application/json.