Swift - 将字典发送到服务器时格式不正确的数据


Swift - malformed data when sending a dictionary to server

在服务器开发过程中,我使用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之前的字典:

["requests": (
        {
        "data_dictionary" =         {
            "first_name" = First;
            password = mypassword;
            "primary_email_address" = "myemail@domain.com";
            surname = Last;
        };
    }
)]

这是服务器的响应:

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

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

这是将数据发送到服务器的函数。请注意,我也检查了 HTTP 方法,它按预期是"PUT":

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'), true) 以便将 json 对象作为关联数组获取。