开发者社区> 问答> 正文

参数是否在http POST请求中传递?

我试图在http POST请求中传递字符串的一些参数。我已经创建了一个字典,然后将该字典转换为数据并将其设置为httpBody,但是当我查看我们的服务器时,没有什么是通过的,我的意思是参数是空的。为什么?我犯了什么错?请帮我找出答案。谢谢。

 {

     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 text did not start with array or object and option to allow fragments not set." UserInfo={NSDebugDescription=JSON text did not start with array or object and option to allow fragments not set.}

展开
收起
游客5akardh5cojhg 2019-12-23 20:53:18 543 0
1 条回答
写回答
取消 提交回答
  • 技术架构师 阿里云开发者社区技术专家博主 CSDN签约专栏技术博主 掘金签约技术博主 云安全联盟专家 众多开源代码库Commiter

    json传搞错了,

    2019-12-28 14:10:56
    赞同 展开评论 打赏
问答排行榜
最热
最新

相关电子书

更多
阿里巴巴HTTP 2.0实践及无线通信协议的演进之路 立即下载
CDN助力企业网站进入HTTPS时代 立即下载
低代码开发师(初级)实战教程 立即下载