gpt4 book ai didi

ios - 带 url 的 datatask 工作正常,而使用 request 调用 datatask 返回的数据末尾带有垃圾

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

我正在使用 URLSession.shared.dataTask 调用 Web 服务。使用带有 url 的 datatask 调用它可以正常工作,而使用 request 调用 datatask 将返回带有“末尾垃圾”的数据。有人可以解释一下为什么吗?以下是两种格式的函数。

使用 URL 调用 dataTask (task = URLSession.shared.dataTask(with: url,completionHandler) 工作正常并返回数据中的有效结果。

basePath 是 Web 服务 URL 的路径

static func getUserDetails(withprefixText prefixText: String, withUserName userName:String, withPassword password:String) {
// Call the web serrvice
urlString = basePath + "?prefixText=" + prefixText + "&prefixText1=" + userName + "&prefixText2=" + password
guard let url = URL(string: urlString) else { return }

let task = URLSession.shared.dataTask(with: url, completionHandler: { (data: Data?,response: URLResponse?,error: Error?) in

if error != nil {
print("error = \(String(describing: error))")
return
}
//Let's convert response sent from a server side script to a NSDictionary object:
do {
let json = try JSONSerialization.jsonObject(with: data! , options: []) as? [String:Any]
if let parseJSON = json {
if let data = parseJSON["data"] as? [[String:Any]] {
Now we can access values by it's key
}
}
else {
print ("Parsing error")
}
} catch {
print("Serilization Error = \(error)")
}
})
task.resume()
}

使用请求调用 dataTask (task = URLSession.shared.dataTask(with: request,completionHandler) 返回数据结果,末尾有垃圾。因此 JSONSerialization.jsonObject 失败,并显示错误“末尾垃圾”

static func getUserDetails(withprefixText prefixText: String, withUserName userName:String, withPassword password:String) {
// Call the web serrvice
let myURL = URL(string: basePath)
var request = URLRequest(url: myURL!)
request.httpMethod = "POST"
request.addValue("application/json", forHTTPHeaderField: "Content-Type")

let postString = ["prefixText": prefixText, "prefixText1": userName, "prefixText2": password] as [String: String]
if JSONSerialization.isValidJSONObject(postString) {
do {
request.httpBody = try JSONSerialization.data(withJSONObject: postString, options: .prettyPrinted)
}
catch let error {
print(error.localizedDescription)
return
}
}

let task = URLSession.shared.dataTask(with: request, completionHandler: { (data: Data?,response: URLResponse?,error: Error?) in

if error != nil {
print("error = \(String(describing: error))")
return
}
do {
let json = try JSONSerialization.jsonObject(with: data! , options: []) as? [String:Any]
if let parseJSON = json {
if let data = parseJSON["data"] as? [[String:Any]] {
// Now we can access values by its key
}

}
else {
print ("Parsing error")
}
} catch {
print("Serilization Error = \(error)")
}
})
task.resume()
}

最佳答案

您的网络服务将参数作为 URLencoding

所以内容类型应该是

"Content-Type" : "application/x-www-form-urlencoded"

你可以这样做

let config = NSURLSessionConfiguration.defaultSessionConfiguration()
config.HTTPAdditionalHeaders = [
"Accept" : "application/json",
"Content-Type" : "application/x-www-form-urlencoded"
]

let session = NSURLSession(configuration: config)

let request = NSMutableURLRequest(URL: NSURL(string:"BASE_URL_SERVER")!)

// this paramter as example just set your paramter
request.encodeParameters(["name" : "email@email.com", "passwordd":"password"])

let task = session.dataTaskWithRequest(request) { data, response, error in
guard error == nil && data != nil else {
print(error)
return
}
// now you can use data to serialize it

}
task.resume()

关于ios - 带 url 的 datatask 工作正常,而使用 request 调用 datatask 返回的数据末尾带有垃圾,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50191937/

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