在服务器开发期间,我使用cURL来测试发布的数据。现在我正在客户端开发,从服务器返回的数据似乎格式不正确。
首先,我会告诉你我用cURL发送的内容:
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"
}
}
] =>
)
)
这是服务器的回复:
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()
}
然后,当我尝试自然地访问密钥“请求”时,服务器回复了未定义的偏移错误。
以下是将数据发送到服务器的功能。注意,我也检查了HTTP方法,并按预期“PUT”:
mNavigationView.post(new Runnable(){ @Override public void run() {and your code}}
目前还值得注意我的代码(我已将其留在此处)并成功使用服务器证书跳过身份验证。
答案 0 :(得分:0)
好的,事实证明实际上我正在发送一个JSON对象,我的服务器期待一个参数字符串。它们是分开的东西。为了解决这个问题,我需要使用json_decode( file_get_contents('php://input'), true)
来将json对象作为关联数组。