使用Alamofire发送带有简单字符串的POST请求

100

如何在我的iOS应用程序中使用Alamofire发送带有简单字符串的POST请求?

作为默认设置,Alamofire需要请求参数:

Alamofire.request(.POST, "http://mywebsite.example/post-request", parameters: ["foo": "bar"])

这些参数包含键值对。但我不想在HTTP主体中发送键值字符串。

我的意思是这样的:

Alamofire.request(.POST, "http://mywebsite.example/post-request", body: "myBodyString")
12个回答

2

我的情况是,我要发布带有"Content-Type":"application/x-www-form-urlencoded"的alamofire内容,我必须更改alamofire post请求的编码方式

从:JSONENCODING.DEFAULT 到:URLEncoding.httpBody

在这里:

let url = ServicesURls.register_token()
    let body = [
        "UserName": "Minus28",
        "grant_type": "password",
        "Password": "1a29fcd1-2adb-4eaa-9abf-b86607f87085",
         "DeviceNumber": "e9c156d2ab5421e5",
          "AppNotificationKey": "test-test-test",
        "RegistrationEmail": email,
        "RegistrationPassword": password,
        "RegistrationType": 2
        ] as [String : Any]


    Alamofire.request(url, method: .post, parameters: body, encoding: URLEncoding.httpBody , headers: setUpHeaders()).log().responseJSON { (response) in

-4

Xcode 8.X,Swift 3.X

易于使用;

 let params:NSMutableDictionary? = ["foo": "bar"];
            let ulr =  NSURL(string:"http://mywebsite.com/post-request" as String)
            let request = NSMutableURLRequest(url: ulr! as URL)
            request.httpMethod = "POST"
            request.setValue("application/json", forHTTPHeaderField: "Content-Type")
            let data = try! JSONSerialization.data(withJSONObject: params!, options: JSONSerialization.WritingOptions.prettyPrinted)

            let json = NSString(data: data, encoding: String.Encoding.utf8.rawValue)
            if let json = json {
                print(json)
            }
            request.httpBody = json!.data(using: String.Encoding.utf8.rawValue);


            Alamofire.request(request as! URLRequestConvertible)
                .responseJSON { response in
                    // do whatever you want here
                   print(response.request)  
                   print(response.response) 
                   print(response.data) 
                   print(response.result)

            }

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接