gpt4 book ai didi

ios - 无法在 api 响应中获得成功

转载 作者:行者123 更新时间:2023-11-29 05:35:05 25 4
gpt4 key购买 nike

这就是我使用 URLSession 发出 api 请求的方式:

let url = URL(string: "http://192.168.1.21.2/FeatureRequestComponent/FeatureRequestComponentAPI")!
var request = URLRequest(url: url)
request.setValue("application/x-www-form-urlencoded", forHTTPHeaderField: "Content-Type")
request.httpMethod = "POST"
let parameters: [String: Any] = [
"AppID": "67B10F42-A372-4D4B-B630-5933E3F7FD65",
"FeatureTitle": "ABCD",
"UserName": "Ayaz",
"UserEmail": self.userEmailTextfield.text ?? "",
"Priority":"H",
"Description": self.featureDescriptionTextView.text ?? "",
"UseCase": self.useCaseTextView.text ?? "",
"DeviceType" : "iPhone"
]
request.httpBody = parameters.percentEscaped().data(using: .utf8)


let task = URLSession.shared.dataTask(with: request) { data, response, error in
guard let data = data,
let response = response as? HTTPURLResponse,
error == nil else { // check for fundamental networking error
print("error", error ?? "Unknown error")
return
}

guard (200 ... 299) ~= response.statusCode else { // check for http errors
print("statusCode should be 2xx, but is \(response.statusCode)")
print("response = \(response)")
return
}

let responseString = String(data: data, encoding: .utf8)
print("responseString = \(responseString)")
}

task.resume()

}

 extension Dictionary {
func percentEscaped() -> String {
return map { (key, value) in
let escapedKey = "\(key)".addingPercentEncoding(withAllowedCharacters: .urlQueryValueAllowed) ?? ""
let escapedValue = "\(value)".addingPercentEncoding(withAllowedCharacters: .urlQueryValueAllowed) ?? ""
return escapedKey + "=" + escapedValue
}
.joined(separator: "&")
}
}



extension CharacterSet {
static let urlQueryValueAllowed: CharacterSet = {
let generalDelimitersToEncode = ":#[]@" // does not include "?" or "/" due to RFC 3986 - Section 3.4
let subDelimitersToEncode = "!$&'()*+,;="

var allowed = CharacterSet.urlQueryAllowed
allowed.remove(charactersIn: "\(generalDelimitersToEncode)\(subDelimitersToEncode)")
return allowed
}()
}

上面我给出了转义百分比的扩展名和字符集

但是我得到的响应是这样的错误:

responseString = Optional("{\"isError\":true,\"ErrorMessage\":\"Unknown Error Occured\",\"Result\":{},\"ErrorCode\":999}")

我在这里做错了什么......?我的回复应该会成功,但我收到的是错误消息。

最佳答案

我尝试检测您代码中的问题,但没有找到

使用我的代码 war ,效果很好

希望对你有帮助

let jsonData = try? JSONSerialization.data(withJSONObject: ["username":username,"password":password])

var request = URLRequest(url: URL(string: "http://api.com/login")!)

request.httpMethod = "POST";
request.addValue("application/json", forHTTPHeaderField: "Accept")
request.addValue("application/json", forHTTPHeaderField: "Content-Type")
request.httpBody = jsonData

let task = URLSession.shared.dataTask(with: request) { data, response, error in
guard let data = data, error == nil else {
print(error?.localizedDescription ?? "No data")
return
}
let dataJSON = try? JSONSerialization.jsonObject(with: data, options: [])
if let responseJSON = dataJSON as? [String: Any] {

DispatchQueue.main.async {

let User = responseJSON["user"] as! [String:Any]

print("user: ", User)
print("name: ", User["name"]!)
print("email: ", User["email"]!)

}

}else {
print("error")
}
}
task.resume()

关于ios - 无法在 api 响应中获得成功,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57111325/

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