Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/php/261.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Php Swift-向服务器发送字典时数据格式不正确_Php_Swift_Curl_Nsurlsession_Nsurlsessiondatatask - Fatal编程技术网

Php Swift-向服务器发送字典时数据格式不正确

Php Swift-向服务器发送字典时数据格式不正确,php,swift,curl,nsurlsession,nsurlsessiondatatask,Php,Swift,Curl,Nsurlsession,Nsurlsessiondatatask,在服务器开发期间,我使用cURL测试发布的数据。现在我在客户端开发,从服务器返回的数据似乎格式不正确 首先,我将向您展示我使用cURL发送的内容: curl -X PUT --data "requests[0][data_dictionary][primary_email_address]=myemail@domain.com&requests[0][data_dictionary][first_name]=First&requests[0][data_dictionary][s

在服务器开发期间,我使用cURL测试发布的数据。现在我在客户端开发,从服务器返回的数据似乎格式不正确

首先,我将向您展示我使用cURL发送的内容:

curl -X PUT --data "requests[0][data_dictionary][primary_email_address]=myemail@domain.com&requests[0][data_dictionary][first_name]=First&requests[0][data_dictionary][surname]=Last&requests[0][data_dictionary][password]=mypassword" -k -L https://localhost/rest/v1/account/create
当我打印出收到的数据时,我得到以下信息:

Request dictionaries: Array
(
    [0] => Array
        (
            [data_dictionary] => Array
                (
                    [primary_email_address] => myemail@domain.com
                    [first_name] => First
                    [surname] => Last
                    [password] => mypassword
                )

        )

)
这就是我所期望的。现在,客户端:

以下是使用NSJSONSerialization类向NSData上交之前的字典:

下面是服务器的响应:

Request dictionaries: Array
(
    [{
__"requests"_:_] => Array
        (
            [
    {
      "data_dictionary" : {
        "first_name" : "First",
        "primary_email_address" : "myemail@domain.com",
        "surname" : "Last",
        "password" : "mypassword"
      }
    }
  ] => 
        )

)
然后,当我尝试访问密钥“请求”时,服务器自然会回复一个未定义的偏移量错误

下面是将数据发送到服务器的函数。注意,我也检查了HTTP方法,它按预期“放置”:

public func fetchResponses(completionHandler: FetchResponsesCompletionHandler)
{
    let session = NSURLSession(configuration: NSURLSessionConfiguration.defaultSessionConfiguration(),
        delegate: self,
        delegateQueue: nil)

    let request = NSMutableURLRequest(URL: requestConfiguration.restURI)
    request.HTTPMethod = requestConfiguration.httpMethod

    if (requestConfiguration.postDictionary != nil)
    {
        print("Dictionary to be posted: \(requestConfiguration.postDictionary!)")


        //  Turn the dictionary in to a JSON NSData object

        let jsonData: NSData

        do
        {
            jsonData = try NSJSONSerialization.dataWithJSONObject(requestConfiguration.postDictionary!, options: [.PrettyPrinted])
        }
        catch let jsonError as NSError
        {
            fatalError("JSON error when encoding request data: \(jsonError)")
        }


        //  Set HTTP Body with the post dictionary's data

        request.HTTPBody = jsonData


        //  Set HTTP headers

        request.setValue("application/json", forHTTPHeaderField: "Content-Type")
        request.setValue("application/json", forHTTPHeaderField: "Accept")

        request.setValue("\(request.HTTPBody!.length)", forHTTPHeaderField: "Content-Length")
    }


    let task = session.dataTaskWithRequest(request) { (data, response, error) in

        //  Check return values

        if error != nil
        {
            fatalError("Request error: \(error)")
        }



        //  Get JSON data

        let jsonDictionary: NSDictionary

        do {
            jsonDictionary = try NSJSONSerialization.JSONObjectWithData(data!, options: []) as! NSDictionary
        }
        catch let jsonError as NSError
        {
            let responseAsString = NSString(data: data!, encoding: NSUTF8StringEncoding)!

            print("Server return data as string: \(responseAsString)")

            fatalError("JSON Error when decoding response data: \(jsonError)")
        }


        //  Do some stuff with the data


        //      Complete with the client responses

        completionHandler(error: nil, responses: clientResponses)
    }

    task.resume()
}

另外值得注意的是,我的代码目前没有显示在这里,并且成功地跳过了服务器证书的身份验证。

好的,因此事实证明我正在发送一个JSON对象,而我的服务器需要一个参数字符串。它们是不同的东西。为了解决这个问题,我需要使用json_decode file_get_contents'php://input,以便将json对象作为关联数组获取

public func fetchResponses(completionHandler: FetchResponsesCompletionHandler)
{
    let session = NSURLSession(configuration: NSURLSessionConfiguration.defaultSessionConfiguration(),
        delegate: self,
        delegateQueue: nil)

    let request = NSMutableURLRequest(URL: requestConfiguration.restURI)
    request.HTTPMethod = requestConfiguration.httpMethod

    if (requestConfiguration.postDictionary != nil)
    {
        print("Dictionary to be posted: \(requestConfiguration.postDictionary!)")


        //  Turn the dictionary in to a JSON NSData object

        let jsonData: NSData

        do
        {
            jsonData = try NSJSONSerialization.dataWithJSONObject(requestConfiguration.postDictionary!, options: [.PrettyPrinted])
        }
        catch let jsonError as NSError
        {
            fatalError("JSON error when encoding request data: \(jsonError)")
        }


        //  Set HTTP Body with the post dictionary's data

        request.HTTPBody = jsonData


        //  Set HTTP headers

        request.setValue("application/json", forHTTPHeaderField: "Content-Type")
        request.setValue("application/json", forHTTPHeaderField: "Accept")

        request.setValue("\(request.HTTPBody!.length)", forHTTPHeaderField: "Content-Length")
    }


    let task = session.dataTaskWithRequest(request) { (data, response, error) in

        //  Check return values

        if error != nil
        {
            fatalError("Request error: \(error)")
        }



        //  Get JSON data

        let jsonDictionary: NSDictionary

        do {
            jsonDictionary = try NSJSONSerialization.JSONObjectWithData(data!, options: []) as! NSDictionary
        }
        catch let jsonError as NSError
        {
            let responseAsString = NSString(data: data!, encoding: NSUTF8StringEncoding)!

            print("Server return data as string: \(responseAsString)")

            fatalError("JSON Error when decoding response data: \(jsonError)")
        }


        //  Do some stuff with the data


        //      Complete with the client responses

        completionHandler(error: nil, responses: clientResponses)
    }

    task.resume()
}