参数未传递到Http post请求上吗? [英] Parameters are not passed on Http post request?

查看:140
本文介绍了参数未传递到Http post请求上吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

Hai我正在尝试在Http post请求中传递一些字符串参数.我创建了一个字典,然后将该字典转换为数据并设置为httpBody.但是当我在我们的服务器上查看时,什么都没有通过,我的意思是参数为空.为什么?我在做什么错误?请帮助我找出答案.谢谢.

Hai I am trying to pass some parameters of string in Http post request. I have created a dictionary and then converted that dictionary to data and set as httpBody.But when I looked on our server nothing has been passd I mean parameters are empty.Why? What mistake i am doing?Please help me to find out.Thanks in advance.

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 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.}

推荐答案

您没有说,但是我假设在打印"json序列化失败并显示错误"时出现了此错误.如果是这样,则CZ54是正确的,您的响应显然不是JSON.因此,在打印该错误的地方,还要打印标题和正文,以查看服务器实际返回的内容(如果有的话):

You don’t say, but I’m assuming you’re getting this error where you print "json serialization failed with error". If so, CZ54 is right, that your response is obviously not JSON. So, where you print that error, also print the header and body to see what the server actually returned, if anything:

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

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

The response header will include the status code (which should be something in the 200...299 range). If it’s not in that range, the status code will tell you the broad nature of the problem.

关于响应主体,有时(特别是在开发环境中)如果服务器阻塞,它可能会返回概述问题性质的HTML页面(尽管,在其他情况下,请注意,它仅输出以下事实:出现错误,但没有详细信息,您需要进入服务器错误日志以找出问题所在).

And regarding the response body, Sometimes (esp in development environments) if the server choked on something, it may return a HTML page outlining the nature of the problem (though, admittedly, in other cases, it only outputs the fact that there was an error, but not the details, and you’ll need to go into the server error logs to figure out what went wrong).

像上面一样,查看响应的详细信息是您的第一步.或者,您可以通过在模拟器上运行应用程序,然后使用 Charles a>或 Wireshark .一旦它们启动并运行,这些都是检查请求和响应的好工具.

Looking at the specifics of the response, like above, is is your first step. Or you can achieve this by running the app on a simulator, and watching the request and the response in a tool like Charles or Wireshark. Once you get them up and running, these are great tools for inspecting requests and responses.

下一个问题是为什么服务器生成了响应.通常,这些问题可能是服务器错误导致的,但更可能的情况是请求格式不正确,服务器不知道如何处理.查看响应(或查看服务器的错误日志)通常可以提供很好的线索.但是,任何人都无法根据所提供的信息为您提供帮助.

The next question is why the server generated the response that it did. As a general rule, while these sorts of problems can be a result of some server mistake, the more likely scenario is that the request wasn’t formed correctly and the server didn’t know how to handle it. Looking at the response (or looking at your server’s error logs) often provides good clues. But there’s no way anyone can help you on the basis of the information provided.

这篇关于参数未传递到Http post请求上吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆