ios 在 Swift 中使用标头发出 HTTP 请求

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/34583840/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-31 08:30:48  来源:igfitidea点击:

Making HTTP Request with header in Swift

iosswiftnsurlsessionimgur

提问by joey

I am trying to make an HTTP request to the Imgur API. I am trying to retrieve all images associated with the tag "cats." The url, according to the Imgur API is: https://api.imgur.com/3/gallery/t/cats

我正在尝试向 Imgur API 发出 HTTP 请求。我正在尝试检索与标签“cats”相关的所有图像。url,根据 Imgur API 是:https: //api.imgur.com/3/gallery/t/cats

the Imgur API states the following about the authorization needed to make get requests:

Imgur API 声明了以下关于发出获取请求所需的授权:

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_idin 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

对于公共只读和匿名资源,例如获取图像信息、查找用户评论等,您需要做的就是client_id在您的请求中发送授权标头。如果您想匿名上传图像(图像
不与帐户绑定),或者您想创建匿名
相册,这也适用。这让我们知道哪个应用程序正在访问 API。

Authorization: Client-ID YOUR_CLIENT_ID

I've looked at the following questions and tried things suggested there, but none of them have helped.

我查看了以下问题并尝试了那里建议的方法,但没有一个有帮助。

JSON NSURLRequest with credentials

带有凭据的 JSON NSURLRequest

Swift GET request with parameters

带参数的 Swift GET 请求

How to make a Http get and set httpHeader in Swift?

如何在 Swift 中制作 Http 获取和设置 httpHeader?

My current code is this:

我目前的代码是这样的:

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()

But I continually get a status code of 403, meaning authorization is required. What am I doing wrong?

但是我不断收到 403 的状态代码,这意味着需要授权。我究竟做错了什么?

回答by

I think you need to prepend Client-IDstring to your actual client ID as for the header value:

我认为您需要将Client-ID字符串添加到您的实际客户端 ID 中作为标头值:

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

回答by Kiran jadhav

Updated for swift 4 :

为 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()
}