【问题标题】:Swift - malformed data when sending a dictionary to serverSwift - 将字典发送到服务器时格式错误的数据
【发布时间】:2015-11-05 17:58:38
【问题描述】:

在服务器开发期间,我使用 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()
}

值得注意的是,我目前的代码(我在这里省略了)并成功跳过了使用服务器证书的身份验证。

【问题讨论】:

    标签: php swift curl nsurlsession nsurlsessiondatatask


    【解决方案1】:

    好的,事实证明,我实际上是在发送一个 JSON 对象,而我的服务器需要一个参数字符串。它们是分开的东西。为了解决这个问题,我需要使用 json_decode( file_get_contents('php://input'), true) 来获取 json 对象作为关联数组。

    【讨论】:

      猜你喜欢
      • 2012-07-12
      • 1970-01-01
      • 2017-05-10
      • 1970-01-01
      • 2018-05-07
      • 1970-01-01
      • 2015-11-17
      • 2020-10-30
      • 1970-01-01
      相关资源
      最近更新 更多