gpt4 book ai didi

swift URLRequest 不发送参数

转载 作者:行者123 更新时间:2023-11-28 15:51:41 26 4
gpt4 key购买 nike

在下面的代码中

    let bodyData = "?sub=\(id)&name=User&email=test@test.com"
let url = NSURL(string: "https://httpbin.org/get");
let request:NSMutableURLRequest = NSMutableURLRequest(url:url as! URL)
request.httpMethod = "GET"
request.httpBody = bodyData.data(using: String.Encoding.utf8);
NSURLConnection.sendAsynchronousRequest(request as URLRequest, queue: OperationQueue.main)
{
(response, data, error) in
if let HTTPResponse = response as? HTTPURLResponse {
let statusCode = HTTPResponse.statusCode

if statusCode == 200 {
// Yes, Do something.
let json = try? JSONSerialization.jsonObject(with: data!, options: [])
if let dictionary = json as? [String: Any] {
let args = dictionary["args"]
NSLog("args:\(args)")
for (key, value) in dictionary{
NSLog("key:\(key) value:\(value)")
}
}
}
}
}

id 是传递给函数的字符串。

它返回了有效数据,但测试站点/url 还会以 json 格式返回您发送给它的任何参数。但是这段代码似乎没有发送 bodyData 中定义的查询参数,我不明白为什么。

最佳答案

如果使用 GET 请求,参数将附加到 URL 并且根本不需要显式 URLRequest

此代码是原生 Swift 3 并使用现代 API:

let id = 12

let bodyData = "?sub=\(id)&name=User&email=test@test.com"
let url = URL(string: "https://httpbin.org/get" + bodyData)!

URLSession.shared.dataTask(with: url) { (data, response, error) in

if error != nil {
print(error!)
return
}

do {
if let json = try JSONSerialization.jsonObject(with: data!, options: []) as? [String:Any],
let args = json["args"] as? [String:Any] {
print("args:\(args)")
for (key, value) in args{
print("key:\(key) value:\(value)")
}
}
} catch {
print(error)
}
}.resume()

关于swift URLRequest 不发送参数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42217835/

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