gpt4 book ai didi

ios - Http post请求没有传递参数?

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

Hai 我正在尝试在 Http post 请求中传递一些字符串参数。我创建了一个字典,然后将该字典转换为数据并设置为 httpBody。但是当我查看我们的服务器时,没有任何内容被传递,我的意思是参数为空。为什么?我犯了什么错误?请帮我找出答案。提前致谢。

func receiptValidation(productId:String,requestFrom:String)
{
let SUBSCRIPTION_SECRET = "mySecretKey"
let defaults = UserDefaults.standard
let receiptPath = Bundle.main.appStoreReceiptURL?.path
if FileManager.default.fileExists(atPath: receiptPath!){
var receiptData:NSData?
do {
receiptData = try NSData(contentsOf: Bundle.main.appStoreReceiptURL!, options: NSData.ReadingOptions.alwaysMapped)
}
catch{
print("ERROR: " + error.localizedDescription)
}
//let receiptString = receiptData?.base64EncodedString(options: NSData.Base64EncodingOptions(rawValue: 0))
let base64encodedReceipt = receiptData?.base64EncodedString(options: NSData.Base64EncodingOptions.endLineWithCarriageReturn)

print(base64encodedReceipt!)
let requestDictionary = ["receipt-data":base64encodedReceipt!,"password":SUBSCRIPTION_SECRET]

guard JSONSerialization.isValidJSONObject(requestDictionary) else { print("requestDictionary is not valid JSON"); return }
do {
let requestData = try JSONSerialization.data(withJSONObject: requestDictionary)
let requestDataString=String(describing: requestData)
let URLForApplication:String = String(format:"%@/api/validate-receipt-data",opcodeDetails["apiProxyBaseUrl"]!) // this works but as noted above it's best to use your own trusted server
SwiftyBeaver.info("URLForApplication Path:\n\(URLForApplication)")
let url:URL! = URL.init(string: URLForApplication)
var request = URLRequest.init(url: url)
request.httpMethod = "POST"
request.addValue("application/json", forHTTPHeaderField: "Content-Type")
let configure = URLSessionConfiguration.background(withIdentifier: Bundle.main.bundleIdentifier!)
session1=URLSession(configuration: .default, delegate: applicationDelegate.application, delegateQueue: OperationQueue.main)

var postString =
["receiptData":requestDataString,
"deviceType":"IOS",
"subscriberId":encodeString(normalString: defaults.array(forKey: "userDetails")?.first as! String),
"password":encodeString(normalString: defaults.array(forKey: "userDetails")?.last as! String),
"productId":encodeString(normalString: productId ),
"code":opcodeDetails["opCode"]!]
do {
request.httpBody = try JSONSerialization.data(withJSONObject: postString, options: .prettyPrinted) // pass dictionary to nsdata object and set it as request body
} catch let error {
print(error.localizedDescription)
}
request.addValue("application/json", forHTTPHeaderField: "Content-Type")

let task = session1?.dataTask(with: request) { (data, response, error) in
if let data = data , error == nil {
do {
let appReceiptJSON = try JSONSerialization.jsonObject(with: data)
print("success. here is the json representation of the app receipt: \(appReceiptJSON)")
// if you are using your server this will be a json representation of whatever your server provided
} catch let error as NSError {
print("json serialization failed with error: \(error)")
}
} else {
print("the upload task returned an error: \(error)")
}
}
task?.resume()
} catch let error as NSError {
print("json serialization failed with error: \(error)")
}
}
}

我收到的错误是Error Domain=NSCocoaErrorDomain Code=3840“JSON文本未以数组或对象开头,并且允许未设置片段的选项。” UserInfo={NSDebugDescription=JSON 文本未以数组或对象开头,并且未设置允许片段的选项。}

最佳答案

你没有说,但我假设你在打印“json 序列化失败并出现错误”时遇到此错误。如果是这样,CZ54 是对的,你的响应显然不是 JSON。因此,在打印该错误的地方,还要打印 header 和正文以查看服务器实际返回的内容(如果有):

print("response header:", response ?? "No response")
print("response body:", String(data: data, using: .utf8) ?? "No body")

响应 header 将包含状态代码(应在 200...299 范围内)。如果不在该范围内,状态代码将告诉您问题的广泛性质。

关于响应正文,有时(特别是在开发环境中)如果服务器因某些原因而阻塞,它可能会返回一个 HTML 页面,概述问题的性质(尽管不可否认,在其他情况下,它只输出以下事实:出现错误,但没有详细信息,您需要进入服务器错误日志以找出问题所在)。

像上面一样,查看回复的具体细节是您的第一步。或者,您可以通过在模拟器上运行应用程序并在 Charles 等工具中观察请求和响应来实现此目的。或Wireshark 。一旦您启动并运行它们,这些都是检查请求和响应的好工具。

下一个问题是为什么服务器生成它所做的响应。一般来说,虽然此类问题可能是由于某些服务器错误造成的,但更可能的情况是请求的格式不正确并且服务器不知道如何处理它。查看响应(或查看服务器的错误日志)通常可以提供很好的线索。但任何人都无法根据所提供的信息为您提供帮助。

关于ios - Http post请求没有传递参数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59452321/

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