【问题标题】:curl -L to get file contents from Box through Alamofire for Swift 3curl -L 通过 Alamofire for Swift 3 从 Box 获取文件内容
【发布时间】:2016-10-31 21:28:52
【问题描述】:

我正在尝试通过他们在 Swift 中的 API 获取 Box 上的文件内容。

curl -L https://api.box.com/2.0/files/file_id/content -H "Authorization: Bearer access_token"

返回正确的内容,但是

curl https://api.box.com/2.0/files/file_id/content -H "Authorization: Bearer access_token"

没有。 所以“-L”部分似乎很关键。

目前为止

    let headers = [
        "grant_type": "client_credentials",
        "Authorization": "Bearer \(token)",
        "scope": "public"
    ]

    Alamofire.request("https://api.box.com/2.0/files/file_id/content", headers: headers).responseJSON { responseFile in

        if let dataFile = responseFile.result.value {
            print("JSON: \(dataFile)")
        }
    }

如何在其中添加“-L”部分?

整体结构应该是正确的,因为我可以通过从 url 中删除“/content”来成功获取文件的元数据。

【问题讨论】:

    标签: ios curl swift3 alamofire


    【解决方案1】:

    根据curl手册-L/--location参数的意思

    如果服务器报告请求的页面已移动到不同的位置(用 Location: 标头和 3XX 响应代码指示),此选项将使 curl 在新位置重做请求。

    所以,我想,您必须检查响应状态代码,如果它是 3xx,您需要处理重定向。检查有关此的 Alamofire 框架文档。

    阅读基础知识也很不错Handling Redirects and Other Request Changes

    【讨论】:

    • 谢谢!我通过获取重定向 url 并提交另一个请求来解决它。
    【解决方案2】:

    根据 a-a-m 的回答,我得到了它使用以下代码。

    请注意,我在第二个请求中使用了 responseString 而不是 responseJSON,因为响应是文件格式而不是 JSON 格式。

        Alamofire.request("https://api.box.com/2.0/files/\(file_id)/content", headers: headers).responseJSON { responseFile in
    
            if let newUrl = responseFile.response?.url {
                print("new link: \(newUrl)")
    
                //make another request using the redirection url
                Alamofire.request(newUrl).responseString { content in 
    
                    let filecontent = content.result.value
                    print (filecontent)
                    self.contentText.text = filecontent
                    debugPrint(contents)
                    }
                }
            }
        }
    

    【讨论】:

      猜你喜欢
      • 2012-09-28
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-04-07
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-02-09
      相关资源
      最近更新 更多