0

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

        )

)

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

NSData这是在上课之前的字典NSJSONSerialization

["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()
}

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

4

1 回答 1

0

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

于 2015-11-05T19:00:01.330 回答