简体   繁体   English

IBM Watson Text To Speech PHP API 问题:无法解码 JSON 对象

[英]IBM Watson Text To Speech PHP API Issue: No JSON object could be decoded

My current PHP code does not seem to work for the IBM Watson Text To Speech.我当前的 PHP 代码似乎不适用于 IBM Watson Text To Speech。

The below code returns the following output:以下代码返回以下输出:

{
   "code_description": "Bad Request", 
   "code": 400, 
   "error": "No JSON object could be decoded"
}"

I have been adding and removing several cURL options, to get it to work, but it still returns the aforementioned error.我一直在添加和删除几个 cURL 选项,以使其正常工作,但它仍然返回上述错误。

<?php

$data="Hello World";

$ch = curl_init();

curl_setopt($ch, CURLOPT_POST, TRUE);
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, 'POST');
curl_setopt($ch, CURLOPT_URL,"https://stream.watsonplatform.net/text-to-speech/api/v1/synthesize");
curl_setopt($ch, CURLOPT_USERPWD, "$USERNAME:$password");
curl_setopt($ch, CURLOPT_SAFE_UPLOAD, TRUE);
curl_setopt($ch, CURLOPT_POSTFIELDS,$data);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE);
curl_setopt($ch, CURLOPT_HEADER, TRUE);
curl_setopt($ch, CURLINFO_HEADER_OUT, TRUE);
curl_setopt($ch, CURLOPT_HTTPHEADER,
    array(
        "Content-Type: application/json",
        "Accept: audio/webm"
    )
);

$server_output = curl_exec($ch);

$status = curl_getinfo($ch, CURLINFO_HTTP_CODE);

$info = curl_getinfo($ch);

curl_close ($ch);

Which header am I supposed to add/remove to get it to work?我应该添加/删除哪个标题才能使其工作?

@blade19899 @blade19899

change this line:改变这一行:

From: curl_setopt($ch, CURLOPT_USERPWD, "$USERNAME:$password");来自: curl_setopt($ch, CURLOPT_USERPWD, "$USERNAME:$password");

To: curl_setopt($ch, CURLOPT_USERPWD, base64_encode("$USERNAME:$password"));至: curl_setopt($ch, CURLOPT_USERPWD, base64_encode("$USERNAME:$password"));

For security reasons a base64 string is expected in authorization header.出于安全原因,需要在授权标头中使用 base64 字符串。 Hope this helps you.希望这对你有帮助。

Since this is the only question found by google for this common problem ... please have in mind that instead of the CURLOPT_USERPWD (which is quite fine for watson without any base64_encode in most cases), the problem here is quit simple and the reply states everything needed: "No JSON object could be decoded"由于这是谷歌针对这个常见问题找到的唯一问题......请记住,而不是 CURLOPT_USERPWD(在大多数情况下,这对于没有任何 base64_encode 的 watson 来说非常好),这里的问题很简单,回复指出所需的一切:“无法解码 JSON 对象”

$data="Hello World"; # <- THIS IS NOT JSON !!!
curl_setopt($ch, CURLOPT_POSTFIELDS,$data);

# try: 
$data='{"text":"Hello World"}';

(that's the simplest way to state JSON) (这是声明 JSON 的最简单方法)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM