我有一个问题是要求Alamofire请求GET ...因为当我发送请求时,我的服务器,收到三个请求,并且该请求是空的....我使用Alamofire并使用One Router, “我在json中发送参数”
case .SearchTravel (let pa1,let pa2,let pa3,let pa4):
let (path: String, parameters: [String: AnyObject]) = {
let parameters = [
"startLat": "12",
"startLng": "12",
"endLat": "12",
"endLng": "21",
]
println(Router.tokenUser)
println(parameters)
return ("travels/Search/", parameters)
}()
let URL = NSURL(string: Router.baseURLString)
let URLRequest = NSMutableURLRequest(
URL: URL!.URLByAppendingPathComponent(path))
//---
URLRequest.HTTPMethod="GET"
if let token = Router.tokenUser {
URLRequest.setValue(
"Token \(token)", forHTTPHeaderField:
"Authorization")
println(token)
}
let encoding = Alamofire.ParameterEncoding.JSON
return encoding.encode(URLRequest, parameters: parameters).0
当我打电话给路由器......
Django.Router.tokenUser=userLogin.token
Alamofire.request(Django.Router.SearchTravel("23", "32", "32", "32")).responseJSON { request, response, JSON, error in
if error==nil{
println("Ok")
}
else{
println(error)
}
但我不知道我的请求是否做得好或问题是什么......
或者构建json请求的方法是什么?
答案 0 :(得分:0)
试试这个
let parameters = [
"startLat": "12",
"startLng": "12",
"endLat": "12",
"endLng": "21",
]
let data = NSJSONSerialization.dataWithJSONObject(parameters, options: NSJSONWritingOptions.PrettyPrinted, error: nil)
let post = NSString(data: data!, encoding: NSUTF8StringEncoding) as! String
httpPost("http://httpbin.org/post", postData: post) {res, c in
println(res)
}
func httpPost(url:String, postData: String, completion: (String, Int) -> Void) {
var request = NSMutableURLRequest(URL: NSURL(string: url)!)
request.HTTPMethod = "POST"
request.HTTPBody = postData.dataUsingEncoding(NSUTF8StringEncoding);
request.addValue("application/x-www-form-urlencoded", forHTTPHeaderField: "Content-Type")
request.addValue("Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/44.0.2403.125 Safari/537.36", forHTTPHeaderField: "User-Agent")
request.addValue("text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8", forHTTPHeaderField: "Accept")
request.addValue("gzip, deflate, sdch", forHTTPHeaderField: "Accept-Encoding")
request.addValue("max-age=0", forHTTPHeaderField: "Cache-Control")
var session = NSURLSession.sharedSession()
let task = session.dataTaskWithRequest(request, completionHandler: { data, response, error in
if let HTTPResponse = response as? NSHTTPURLResponse {
let statusCode = HTTPResponse.statusCode
completion(NSString(data: data, encoding: NSUTF8StringEncoding) as! String, statusCode)
}
})
task.resume()
}