swift - 使用 Swift 请求错误 Google Cloud NLP API

标签 swift google-cloud-platform alamofire sentiment-analysis google-natural-language

我正在尝试向 Google Cloud NLP API 发出请求以获取一段文本的情感分析。我使用 Postman 设计了正确的请求,并且能够使用 Postman 获得有效的响应。但是,当我尝试从 Swift 发出相同的请求时,它给了我一个错误。用于发出请求的错误和代码片段如下所示。

 func sendAPIRequest(with text: String){

    print("Text: ", text)
    let jsonRequest = [
        [
        "document":[
            "type":"PLAIN_TEXT",
            "language": "EN",
            "content":"'Lawrence of Arabia' is a highly rated film biography about British Lieutenant T. E. Lawrence. Peter O'Toole plays Lawrence in the film."
        ],
        "encodingType":"UTF8"
    ]
        ]

    let jsonObject = JSON(jsonRequest)


    let headers: HTTPHeaders = [
        "X-Ios-Bundle-Identifier": "\(Bundle.main.bundleIdentifier ?? "") ",
        "Content-Type": "application/json"
    ]
    let APIRequest = Alamofire.request("https://language.googleapis.com/v1/documents:analyzeSentiment?key=\(gCloudAPIKey)", method: .post , parameters: jsonRequest as? [String: Any], encoding: JSONEncoding.default , headers: headers).responseJSON { (response) in
        print(response)
        if let json = response.result.value {
            print("JSON: \(json)")
        }
    }

错误:

JSON: {
error =     {
    code = 400;
    details =         (
                    {
            "@type" = "type.googleapis.com/google.rpc.BadRequest";
            fieldViolations =                 (
                                    {
                    description = "Must have some text content to annotate.";
                    field = "document.content";
                }
            );
        }
    );
    message = "One of content, or gcs_content_uri must be set.";
    status = "INVALID_ARGUMENT";
};
}

最佳答案

对不起。解决了。根据 Alamofire,我的 jsonRequest 应该是参数类型。

 let jsonRequest: Parameters =
        [
        "document":[
            "type":"PLAIN_TEXT",
            "language": "EN",
            "content":"\(text)"
        ],
        "encodingType":"UTF8"
    ]

关于swift - 使用 Swift 请求错误 Google Cloud NLP API,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51664903/

相关文章:

Docker - 错误 : Cannot perform an interactive login from a non TTY device (GCP Service Account)

swift - Alamofire 库 Void 不可转换为 Response<AnyObject, NSError> -> Void

ios - Swift 4.2 - Alamofire 突然不工作

google-cloud-platform - GCP : How to get compute engine access token?

ios - 如何使用没有下划线的 NSMutableAttributedString 添加链接?

Swift - 在扩展中获取类名?

ios - 如何在 Google maps ios sdk 中过滤自动完成国家?

kubernetes - 升级到GKE中的更大节点池

ios - 在 iOS 上使用 Alamofire 的 Twilio POST 请求

swift - 将 rightBarButtonItem 设为粗体