gpt4 book ai didi

ios - 如何在 swift 中正确添加 http header "Connection :close"?

转载 作者:搜寻专家 更新时间:2023-11-01 05:37:19 24 4
gpt4 key购买 nike

我有一个 swift 应用程序。它向我自己无法访问的服务器发送 http 请求。

当应用程序在后台运行一段时间后,我返回并尝试向服务器发送请求时,我收到一个 http 错误“连接丢失”。

我读了这个post

我想按照建议添加 connection:close header 和值。

我试过这段代码:

func taskForGETMethod(method: String, pathParameters: [String], parameters: [String : AnyObject], completionHandler: (result: AnyObject!, error: NSError?) -> Void) -> NSURLSessionDataTask {

/* 1. Build the URL and configure the request */
let urlString = Constants.BaseURLSecure + method + HttpClient.escapedPath(pathParameters) + HttpClient.escapedParameters(parameters)
let url = NSURL(string: urlString)!
let request = NSURLRequest(URL: url)
request.setValue("Connection", forKey: "close")

但我所有的请求现在都失败了。如何正确添加 header ?

最佳答案

如果你想操作你需要使用 NSMutableURLRequest 和下面的 API 的 http header 值

func setValue(_ value: String?, forHTTPHeaderField field: String)

像这样

let url = NSURL(string: "http://yo", relativeToURL: nil)
let req = NSMutableURLRequest(URL: url!)
req.setValue("close", forHTTPHeaderField: "Connection")

swift 3

let url = URL(string: "http://yo", relativeTo: nil)
let req = NSMutableURLRequest(url: url! )
req.setValue("close", forHTTPHeaderField: "Connection")

关于ios - 如何在 swift 中正确添加 http header "Connection :close"?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35441584/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com