。我在這裏看到了一些快速解析Json的問題,但我的問題與其他問題有點不同。 當我寫/ cmd =登錄& params {'user':'username','password':'pass'}它返回正確的數據。如何快速解決此問題 我發送用戶名和密碼到url作爲json,但 它檢索錯誤,這意味着「無效格式」 請幫助我。 這裏是我曾嘗試:如何使用swift發送Json作爲參數在URL中我使用swift語言創建新的
var url:NSURL = NSURL(string: "http://<host>?cmd=login")!
//var session = NSURLSession.sharedSession()
var responseError: NSError?
var request = NSMutableURLRequest(URL: url!, cachePolicy: NSURLRequestCachePolicy.ReloadIgnoringLocalCacheData, timeoutInterval: 5)
// var request:NSMutableURLRequest = NSMutableURLRequest(URL: url)
var response: NSURLResponse?
request.HTTPMethod = "POST"
let jsonString = "params={\"user\":\"username\",\"password\":\"pass\"}"
request.HTTPBody = jsonString.dataUsingEncoding(NSUTF8StringEncoding, allowLossyConversion:true)
request.setValue("application/json; charset=UTF-8", forHTTPHeaderField: "Content-Type")
// send the request
NSURLConnection.sendSynchronousRequest(request, returningResponse: &response, error: &responseError)
// look at the response
if let httpResponse = response as? NSHTTPURLResponse {
println("HTTP response: \(httpResponse.statusCode)")
} else {
println("No HTTP response")
}
let task = NSURLSession.sharedSession().dataTaskWithRequest(request){
data, response, error in
if error != nil {
println("error=\(error)")
return
}
println("****response= \(response)")
let responseString = NSString(data: data, encoding: NSUTF8StringEncoding)
println("**** response =\(responseString)")
var err: NSError?
var json = NSJSONSerialization.JSONObjectWithData(data, options: NSJSONReadingOptions.MutableContainers , error: &err) as? NSDictionary
}
task.resume()
您是否需要以JSON形式發送?爲什麼不作爲?user = username&?password = pass? 我會建議看看Alamofire的Swift HTTP請求。 https://github.com/Alamofire/Alamofire – Chackle
jsonString不是有效的json,它需要是'「{\」params \「:{\」user \「:\」username \「,\」password \ 「:\」pass \「}}」''除非它不需要是 – sketchyTech
params = {'user':'username','password':'pass'}它在瀏覽器中運行良好 – Vidul