【问题标题】:Request error Google Cloud NLP API with Swift使用 Swift 请求错误 Google Cloud NLP API
【发布时间】:2018-08-03 03:27:20
【问题描述】:

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

 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";
};
}

【问题讨论】:

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


    【解决方案1】:

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

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-07-26
      • 2018-06-17
      • 1970-01-01
      • 2013-11-29
      • 1970-01-01
      相关资源
      最近更新 更多