在Swift中执行POST请求

我正在尝试做这样的事情:

NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:@"http://google.com"]]; request.HTTPMethod = @"POST"; NSString *stringData = @"some data"; NSData *requestBodyData = [stringData dataUsingEncoding:NSUTF8StringEncoding]; request.HTTPBody = requestBodyData; NSURLConnection *conn = [[NSURLConnection alloc] initWithRequest:request delegate:self]; 

这是我迄今为止:

 var url = NSURL(string: "some url") var request = NSMutableURLRequest(URL: url) request.HTTPMethod = "POST" var dataString = "some data" var requestBodyData: NSData = dataString.stringByAddingPercentEscapesUsingEncoding(NSUTF8StringEncoding) as NSData request.HTTPBody = requestBodyData var connection = NSURLConnection(request: request, delegate: self, startImmediately: false) println("sending request...") connection.start() 

然而,var requestBodyData:行抛出第一个石头与“不能转换expression式的typesNSDatatypesNSData”

任何人都在意称重?

stringByAddingPercentEscapesUsingEncoding返回一个string,而不是一个NSData对象。 根据这个答案,你需要使用它来转换为一个NSData实例:

 let data = (anySwiftString as NSString).dataUsingEncoding(NSUTF8StringEncoding) 

使用Alamofire发送HTTP POST请求

 let request = NSMutableURLRequest(URL: NSURL(string: "https://www.google.com")!) request.HTTPMethod = "POST" let body = "email=\(email)&access_token=\(token)" request.HTTPBody = body.dataUsingEncoding(NSUTF8StringEncoding) Alamofire.request(request).responseJSON { response in NSLog("response.request: \(response.request)") // original URL request NSLog("esponse.response: \(response.response)") // URL response switch response.result { case .Success: NSLog("Validation Successful") case .Failure(let error): // Logout NSLog("\(error), \(String(data: response.data!, encoding: NSUTF8StringEncoding))") return } // Save sip account information to NSUserdefaults if let json = response.result.value as? [String: AnyObject]{ // Do your stuff } }