如何在Swift中发送POST参数?

时间:2014-07-12 15:44:13

标签: ios swift

这里有一些代码:

var URL: NSURL = NSURL(string: "http://stackoverflow.com")
var request:NSMutableURLRequest = NSMutableURLRequest(URL:URL)
request.HTTPMethod = "POST"
request.HTTPBody = ?????? 
NSURLConnection.sendAsynchronousRequest(request, queue: NSOperationQueue.mainQueue()) 
{
    (response, data, error) in
    println(NSString(data: data, encoding: NSUTF8StringEncoding))
}

如果我想发送POST查询request.HTTPBody,我应该在"key" = "value"写什么?

4 个答案:

答案 0 :(得分:53)

与Objective-C没有什么不同,HTTPBody需要一个NSData对象:

var bodyData = "key1=value&key2=value&key3=value"
request.HTTPBody = bodyData.dataUsingEncoding(NSUTF8StringEncoding);

您必须设置值&把自己键入字符串。

答案 1 :(得分:2)

希望它有用

在项目中导入alamofire.swift文件

func goLive () {
    var url:String = "Your url"!
    url += "user/login"
    var param = ["email": self.txtmail.text, "password":self.txtpassword.text]
    request(.POST, url, parameters: param)
        .responseJSON { (_, _, JSON, _) in
            //println(JSON)
            if let gData = JSON as? NSDictionary {
                println(gData)
            } else {
                let alert=UIAlertView()
                alert.title="Alert"
                alert.message=gData.valueForKey("message")as? String
                alert.addButtonWithTitle("OK")
                alert.show()
            }
        }
    }
}

答案 2 :(得分:1)

  

更新到Swift 4.2

此代码基于 pixels 的答案,并且是Swift 4.2

的更新
let bodyData = "key1=value&key2=value&key3=value"
request.httpBody = bodyData.data(using: .utf8)

答案 3 :(得分:-1)

 var post:NSString = "api=myposts&userid=\(uid)&page_no=0&limit_no=10"

    NSLog("PostData: %@",post);

    var url1:NSURL = NSURL(string: url)!

    var postData:NSData = post.dataUsingEncoding(NSASCIIStringEncoding)!

    var postLength:NSString = String( postData.length )

    var request:NSMutableURLRequest = NSMutableURLRequest(URL: url1)
    request.HTTPMethod = "POST"
    request.HTTPBody = postData
    request.setValue(postLength, forHTTPHeaderField: "Content-Length")
    request.setValue("application/x-www-form-urlencoded", forHTTPHeaderField: "Content-Type")
    request.setValue("application/json", forHTTPHeaderField: "Accept")


    var reponseError: NSError?
    var response: NSURLResponse?

    var urlData: NSData? = NSURLConnection.sendSynchronousRequest(request, returningResponse:&response, error:&reponseError)

    if ( urlData != nil ) {
        let res = response as NSHTTPURLResponse!;

        NSLog("Response code: %ld", res.statusCode);

        if (res.statusCode >= 200 && res.statusCode < 300)
        {
            var responseData:NSString  = NSString(data:urlData!, encoding:NSUTF8StringEncoding)!

            NSLog("Response ==> %@", responseData);

            var error: NSError?

            let jsonData:NSDictionary = NSJSONSerialization.JSONObjectWithData(urlData!, options:NSJSONReadingOptions.MutableContainers , error: &error) as NSDictionary


            let success:NSInteger = jsonData.valueForKey("error") as NSInteger

            //[jsonData[@"success"] integerValue];

            NSLog("Success: %ld", success);

            if(success == 0)
            {
                NSLog("Login SUCCESS");

                self.dataArr = jsonData.valueForKey("data") as NSMutableArray 
                self.table.reloadData()

            } else {

                NSLog("Login failed1");
            }

        } else {

            NSLog("Login failed2");

        }
    } else {

         NSLog("Login failed3");
    }

这肯定会帮助你