gpt4 book ai didi

swift - NSURLSession 参数无法识别

转载 作者:行者123 更新时间:2023-11-30 13:31:51 24 4
gpt4 key购买 nike

我正在尝试使用 NSURLSession 发出 HTTPRequest。当我设置完整的 url 时,请求返回正确的数据,但是当使用参数时 (NSJSONSerialization.dataWithJSONObject -> HTTPBody 我收到此错误

error Domain=NSURLErrorDomain Code=-1005 "The network connection was lost."

我在这里做错了什么吗?

 let json = ["api_key": "XXXXXXXXXXXXXXXXXXXXXXXXXXXXXX"]
do {

let jsonData = try NSJSONSerialization.dataWithJSONObject(json, options: .PrettyPrinted)

let url = NSURL(string: "https://api.themoviedb.org/3/discover/movie")!
let request = NSMutableURLRequest(URL: url)
request.HTTPBody = jsonData
request.HTTPMethod = "GET"
request.setValue("application/json; charset=utf-8", forHTTPHeaderField: "Content-Type")


let task = NSURLSession.sharedSession().dataTaskWithRequest(request){ data, response, error in
if error != nil{
print("Error -> \(error)")
return
}
do {
let result = try NSJSONSerialization.JSONObjectWithData(data!, options: []) as? [String:AnyObject]

print("Result -> \(result)")

} catch {
print("Error -> \(error)")
}
}

task.resume()


} catch {
print(error)
}
}

这不是重复的!在问这个问题之前,我查看了建议的答案(没有一个有效)

最佳答案

在您的情况下,可以通过将 request.HTTPMethod = "GET" 更改为 request.HTTPMethod = "POST" 来解决该问题

您不应该在 get 请求中发送 HTTP Body,要通过正文发送数据,您应该将 HTTPMethod 更改为 post

注意:请检查此api方法是否支持POST请求,如果不支持post,则不能将其与http body/post一起使用,根据文档我只找到“get”对 discover/movie 的请求可以是这样的:

let url = NSURL(string: "http://api.themoviedb.org/3/discover/movie?api_key=YOUR_API_KEY")!
let request = NSMutableURLRequest(URL: url)
request.addValue("application/json", forHTTPHeaderField: "Accept")

let session = NSURLSession.sharedSession()
let task = session.dataTaskWithRequest(request) { data, response, error in
if let response = response, data = data {
print(response)
print(String(data: data, encoding: NSUTF8StringEncoding))
} else {
print(error)
}
}

task.resume()

引用:您可以通过此网址查看更多信息:http://docs.themoviedb.apiary.io/#reference/discover/discovermovie/get

关于swift - NSURLSession 参数无法识别,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36490972/

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