我正在尝试通过Mandrill API发送电子邮件。 我在下面找到了用于JSON HTTP POST方法的快速代码here:
func createRequest(myUrl : String, type : String, params : NSDictionary?, completion : (AnyObject?, NSError?)->Void ){
var url = NSURL(string: myUrl)
var request = NSMutableURLRequest(URL: url!, cachePolicy: NSURLRequestCachePolicy.UseProtocolCachePolicy, timeoutInterval: 60.0)
if params != nil {
var data = NSJSONSerialization.dataWithJSONObject(params!, options: NSJSONWritingOptions.PrettyPrinted, error: nil)
request.setValue("\(data!.length)", forHTTPHeaderField: "Content-Length")
request.HTTPBody = data
}
request.setValue("application/json", forHTTPHeaderField:"Content-type")
request.setValue("application/json", forHTTPHeaderField: "Accept")
request.HTTPMethod = type
NSURLConnection.sendAsynchronousRequest(request, queue: NSOperationQueue(),
completionHandler: {(response: NSURLResponse!, data: NSData!, error: NSError!) in
var returnedObject : AnyObject! = NSJSONSerialization.JSONObjectWithData(data, options: NSJSONReadingOptions.MutableLeaves, error: nil)
completion(returnedObject,error)
})
}
现在我设置我的网址和参数如下:
let url = "https://mandrillapp.com/api/1.0/messages/send.json"
let to = ["email" : "xyz@gmail.com"]
let message = [
"from_email" : "noreply@abc.com",
"from_name" : "abc",
"subject" : "Message through abc",
"text" : "sample message",
"to" : to
]
let params = [
"key": "myKey",
"message" : message
]
然后我这样调用这个函数:
createRequest(url, type: "POST", params: params, completion: {(returnedObject : AnyObject?, error : NSError?)in
if (returnedObject != nil) {
println("data = \(returnedObject)")
}
})
但我得到错误:
data = Optional({
code = "-2";
message = "Validation error: {\"message\":{\"to\":[\"Please enter an array\"]}}";
name = ValidationError;
status = error;
})
我做错了什么?
答案 0 :(得分:1)
我不知道您正在使用的框架(甚至编程语言),但响应似乎非常清楚。
这就是事情:
let to = [“email”:“xyz@gmail.com”]
这对我来说显然看起来不像是一个数组,看起来更像是一本字典(或者说是语言中的等价物)。我认为以下方法可行:
let to = [“xyz@gmail.com”]
修改强>
也许,这会:
“to”:[ { “email”:“recipient.email@example.com”, “名称”:“收件人姓名”, “type”:“to” } ]
我的下一个猜测是名称和类型不是可选的..而且“to”字段需要一个字典项数组。
答案 1 :(得分:1)
最后!!!我自己想通了。
let to = ["email" : "kashif.izhar@gmail.com"]
应该是
let to = [["email" : "kashif.izhar@gmail.com"]]
希望它有助于某人