如何在Swift中使用JSON主体进行HTTP Post请求
我正在尝试使用JSON主体进行HTTP发布请求:
如何能够将一个NSdictionnary添加到HTTP请求体。
这是我的代码,它似乎不能正常工作。
var entry1 = Response(IdQuestion: 6510,IdProposition: 10,Time: 30) var entry2 = Response(IdQuestion: 8284,IdProposition: 10,Time: 30) Responses.append(entry1) Responses.append(entry2) let list = Responses.map { $0.asDictionary } let json = ["List":list,"IdSurvey":"102","IdUser":"iOSclient","UserInformation":"iOSClient"] let data : NSData = NSKeyedArchiver.archivedDataWithRootObject(json) NSJSONSerialization.isValidJSONObject(json) let myURL = NSURL(string: "http://www.myserver.com")! let request = NSMutableURLRequest(URL: myURL) request.HTTPMethod = "POST" request.setValue("application/x-www-form-urlencoded", forHTTPHeaderField: "Content-Type") request.setValue("application/json", forHTTPHeaderField: "Accept") request.HTTPBody = data let task = NSURLSession.sharedSession().dataTaskWithRequest(request) { data, response, error in println(response) // Your completion handler code here } task.resume()
尝试这个,
// prepare json data let json: [String: Any] = ["title": "ABC", "dict": ["1":"First", "2":"Second"]] let jsonData = try? JSONSerialization.data(withJSONObject: json) // create post request let url = URL(string: "http://httpbin.org/post")! var request = URLRequest(url: url) request.httpMethod = "POST" // insert json data to the request request.httpBody = jsonData let task = URLSession.shared.dataTask(with: request) { data, response, error in guard let data = data, error == nil else { print(error?.localizedDescription ?? "No data") return } let responseJSON = try? JSONSerialization.jsonObject(with: data, options: []) if let responseJSON = responseJSON as? [String: Any] { print(responseJSON) } } task.resume()
或尝试一个方便的方式Alamofire
HTTP发布在Swift捕获错误
let json = [ Activity.KEY_IDSUBJECT : activity.idSubject, Activity.KEY_RECORDMODE : "3", Activity.KEY_LOCATION_LONGITUDE : "0",Activity.KEY_LOCATION_LATITUDE : "0", Activity.KEY_CHECKIN : String(activity.dateCheckIn), Activity.KEY_CHECKOUT : String(activity.dateCheckOut) ] do { let jsonData = try NSJSONSerialization.dataWithJSONObject(json, options: .PrettyPrinted) // create post request let url = NSURL(string: "https://...appspot.com/_ah/api/activityendpoint/v1/activity")! let request = NSMutableURLRequest(URL: url) request.HTTPMethod = "POST" // insert json data to the request request.setValue("application/json; charset=utf-8", forHTTPHeaderField: "Content-Type") request.HTTPBody = jsonData let task = NSURLSession.sharedSession().dataTaskWithRequest(request){ data, response, error in if error != nil{ print("Error -> \(error)") return } do { let result = try NSJSONSerialization.JSONObjectWithData(data!, options: []) as? [String:AnyObject] print("Result -> \(result)") } catch { print("Error -> \(error)") } } task.resume() return task } catch { print(error) }
Swift 3
HTTP POST请求使用Swift 3.0中的URLSession API进行error handling
func submitAction(sender: AnyObject) { //declare parameter as a dictionary which contains string as key and value combination. let parameters = ["name": nametextField.text, "password": passwordTextField.text] as [String: String] //create the url with NSURL let url = NSURL(string: "http://myServerName.com/api") //create the session object let session = URLSession.shared //now create the NSMutableRequest object using the url object let request = NSMutableURLRequest(url: url! as URL) request.httpMethod = "POST" //set http method as POST do { request.httpBody = try JSONSerialization.data(withJSONObject: parameters, options: .prettyPrinted) // pass dictionary to nsdata object and set it as request body } catch let error { print(error.localizedDescription) } //HTTP Headers request.addValue("application/json", forHTTPHeaderField: "Content-Type") request.addValue("application/json", forHTTPHeaderField: "Accept") //create dataTask using the session object to send data to the server let task = session.dataTask(with: request as URLRequest, completionHandler: { data, response, error in guard error == nil else { return } guard let data = data else { return } do { //create json object from data if let json = try JSONSerialization.jsonObject(with: data, options: .mutableContainers) as? [String: AnyObject] { print(json) // handle json... } } catch let error { print(error.localizedDescription) } }) task.resume() }
你可以做这样的事情:
func HTTPPostJSON(url: String, data: NSData, callback: (String, String?) -> Void) { var request = NSMutableURLRequest(URL: NSURL(string: url)!) request.HTTPMethod = "POST" request.addValue("application/json",forHTTPHeaderField: "Content-Type") request.addValue("application/json",forHTTPHeaderField: "Accept") request.HTTPBody = data HTTPsendRequest(request, callback: callback) } func HTTPsendRequest(request: NSMutableURLRequest, callback: (String, String?) -> Void) { let task = NSURLSession.sharedSession() .dataTaskWithRequest(request) { (data, response, error) -> Void in if (error != nil) { callback("", error.localizedDescription) } else { callback(NSString(data: data, encoding: NSUTF8StringEncoding)! as String, nil) } } task.resume() } //use var data :Dictionary<String, AnyObject> = yourDictionaryData<-- var requestNSData:NSData = NSJSONSerialization.dataWithJSONObject(request, options:NSJSONWritingOptions(0), error: &err)! HTTPPostJSON("http://yourPosturl..", data: requestNSData) { (response, error) -> Void in if error != nil{ //error return; } println(response); }
下面的Swift 3 Playground代码展示了使用JSONSerialization
和URLSession
解决您的问题的可能方法:
import UIKit import PlaygroundSupport PlaygroundPage.current.needsIndefiniteExecution = true let url = URL(string: "http://localhost:8080/new")! let jsonDict = ["firstName": "Jane", "lastName": "Doe"] let jsonData = try! JSONSerialization.data(withJSONObject: jsonDict, options: []) var request = URLRequest(url: url) request.httpMethod = "post" request.setValue("application/json", forHTTPHeaderField: "Content-Type") request.httpBody = jsonData let task = URLSession.shared.dataTask(with: request) { (data, response, error) in if let error = error { print("error:", error) return } do { guard let data = data else { return } guard let json = try JSONSerialization.jsonObject(with: data, options: []) as? [String: AnyObject] else { return } print("json:", json) } catch { print("error:", error) } } task.resume()
//准备json数据let mapDict = [“1”:“First”,“2”:“Second”]
let json = [ "title":"ABC" , "dict": mapDict ] as [String : Any] let jsonData : NSData = NSKeyedArchiver.archivedData(withRootObject: json) as NSData // create post request let url = NSURL(string: "http://httpbin.org/post")! let request = NSMutableURLRequest(url: url as URL) request.httpMethod = "POST" // insert json data to the request request.httpBody = jsonData as Data let task = URLSession.shared.dataTask(with: request as URLRequest){ data,response,error in if error != nil{ return } do { let result = try JSONSerialization.jsonObject(with: data!, options: []) as? [String:AnyObject] print("Result",result!) } catch { print("Error -> \(error)") } } task.resume()
var request = URLRequest(url: URL(string: "http://yogpande.apphb.com/api/my/posttblhouse")!) request.httpMethod = "POST" let postString = "email=testname@gmail.com&password=1234567" request.httpBody = postString.data(using: .utf8) let task = URLSession.shared.dataTask(with: request) { data, response, error in guard let data = data, error == nil else { print("error=(error)") return } if let httpStatus = response as? HTTPURLResponse, httpStatus.statusCode != 200 { print("statusCode should be 200, but is \(httpStatus.statusCode)") print("response = \(response)") } let responseString = String(data: data, encoding: .utf8) print("responseString = \(responseString)") } task.resume() }
var request = URLRequest(url: URL(string: "your URL")!) request.httpMethod = "POST" let postString = String(format: "email=%@&lang=%@", arguments: [txt_emailVirify.text!, language!]) print(postString) emailString = txt_emailVirify.text! request.httpBody = postString.data(using: .utf8) request.addValue("delta141forceSEAL8PARA9MARCOSBRAHMOS", forHTTPHeaderField: "Authorization") request.addValue("application/x-www-form-urlencoded", forHTTPHeaderField: "Content-Type") request.addValue("application/json", forHTTPHeaderField: "Accept") let task = URLSession.shared.dataTask(with: request) { data, response, error in guard let data = data, error == nil else { print("error=\(String(describing: error))") return } do { let dictionary = try JSONSerialization.jsonObject(with: data, options: .allowFragments) as! NSDictionary print(dictionary) let status = dictionary.value(forKey: "status") as! String let sts = Int(status) DispatchQueue.main.async() { if sts == 200 { print(dictionary) } else { self.alertMessageOk(title: self.Alert!, message: dictionary.value(forKey: "message") as! String) } } } catch { print(error) } } task.resume()