使用Swift发送带有头部的HTTP请求

16
我正在尝试向Imgur API发出HTTP请求。 我正在尝试检索与标签“cats”相关联的所有图像。 根据Imgur API,网址为:https://api.imgur.com/3/gallery/t/cats Imgur API关于进行get请求所需授权的说明如下:

For public read-only and anonymous resources, such as getting image info, looking up user comments, etc. all you need to do is send an authorization header with your client_id in your requests. This also works if you'd like to upload images anonymously (without the image
being tied to an account), or if you'd like to create an anonymous
album. This lets us know which application is accessing the API.

Authorization: Client-ID YOUR_CLIENT_ID

我已经查看了以下问题并尝试了其中提出的建议,但它们都没有帮助。

如何在JSON NSURLRequest中添加凭据

如何在Swift中进行带参数的GET请求

如何在Swift中进行Http get并设置httpHeader?

我的当前代码如下:

let string = "https://api.imgur.com/3/gallery/t/cats"
let url = NSURL(string: string)
let request = NSMutableURLRequest(URL: url!)
request.setValue("clientIDhere", forHTTPHeaderField: "Authorization")
//request.addValue("clientIDhere", forHTTPHeaderField: "Authorization")
request.HTTPMethod = "GET"
let session = NSURLSession.sharedSession()

let tache = session.dataTaskWithRequest(request) { (data, response, error) -> Void in
    if let antwort = response as? NSHTTPURLResponse {
        let code = antwort.statusCode
        print(code)
    }
}
tache.resume()

但是我一直得到403状态码,意味着需要授权。我做错了什么?

问题说明可能有误,因为未授权的HTTP GET请求在Chrome浏览器中返回了401:“{"data": {"error": "需要身份验证", "request": "\ / 3 \ / gallery \ / t \ / cats", "method": "GET"}, "success": false, "status": 401}” 的授权错误代码。403是“禁止”,意味着无论授权多少次也无法获取该页面,因为它是一个被锁定的区域。 - BaseZen
当我将URL复制粘贴到浏览器中时,我得到了同样的响应,即401状态码。但是在Xcode中运行它时,状态代码为403。如果我删除Xcode中的request.setValue方法,则状态代码会更改为401。 - jjjjjjjj
2个回答

26

我认为你需要在实际客户端ID前添加Client-ID字符串作为头部值:

request.setValue("Client-ID <your_client_id>", forHTTPHeaderField: "Authorization")

你能帮我吗?我正在使用Google Books API做同样的事情,但是我一直收到“无效凭据”的错误提示。如果你能帮我,请告诉我。 - Salman Ali

5

已更新至 Swift 4:

func fetchPhotoRequest(YOUR_CLIENT_ID: String)  {
    let string = "https://photoslibrary.googleapis.com/v1/albums"
    let url = NSURL(string: string)
    let request = NSMutableURLRequest(url: url! as URL)
    request.setValue(YOUR_CLIENT_ID, forHTTPHeaderField: "Authorization") //**
    request.httpMethod = "GET"
    request.addValue("application/json", forHTTPHeaderField: "Content-Type")
    let session = URLSession.shared

    let mData = session.dataTask(with: request as URLRequest) { (data, response, error) -> Void in
        if let res = response as? HTTPURLResponse {
            print("res: \(String(describing: res))")
            print("Response: \(String(describing: response))")
        }else{
            print("Error: \(String(describing: error))")
        }
    }
    mData.resume()
}

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接