从appcelerator调用google云视觉API时,为什么会收到无效的JSON有效负载?

时间:2016-03-09 07:47:28

标签: google-api appcelerator appcelerator-titanium google-vision

我正在尝试使用Alloy Appcelerator的Google vision API v1

我创建了一个请求HTTPClient并调用API https://vision.googleapis.com/v1/images:annotate?key=MY_APP_KEY

但是我收到了来自谷歌的回复文字:

  {
 error = {
     code = 400;
     details = (
                  {
                     "@type" = "type.googleapis.com/google.rpc.BadRequest";
                      fieldViolations = ({
                                        description = "Invalid JSON payload received. Unknown name \"request\": Cannot bind query parameter. Field 'request' could not be found in request message.";
                                        });
                  }
                );
     message = "Invalid JSON payload received. Unknown name \"request\": Cannot bind query parameter. Field 'request' could not be found in request message.";
     status = "INVALID_ARGUMENT";
  };

}

我的代码使用Alloy的HTTP请求

var requests =  
{
  "requests":[
    {
      "image":{
        "content": "image_have_encodebase64",
      },
      "features":[
        {
          "type":"TEXT_DETECTION",
          "maxResults":1
        }
      ]
    }
  ]
};
var xhr = Titanium.Network.createHTTPClient();
xhr.open("POST", 'https://vision.googleapis.com/v1/images:annotate?key=MY_APP_KEY');
xhr.send(JSON.stringify(requests));

感谢您的帮助

1 个答案:

答案 0 :(得分:5)

通过设置Content-LengthContent-Type标题,它应该有效:

xhr.setRequestHeader("Content-Length", size);
xhr.setRequestHeader("Content-Type", "application/json");

另外请注意,Google建议您将图片大小调整为1024 x 768 - 您可以使用以下方式调整图片大小:

img = img.imageAsResized(1024,768);

对我的代码进行了这些更改后,我完成了所有工作。

相关问题