如何在Swift中发送这样的HTTP POST?

时间:2016-06-09 01:05:21

标签: ios json swift http swift2

{
  "appId":"YOUR_APP_ID",
  "appKey":"YOU_APP_KEY",
  "queries":{
    "item_name":"Kids Fries",
    "brand_name":"McDonalds"
  }
}

我知道如何处理postString中的前两项(appId,appKey),但我不知道格式是什么"查询",我尝试了以下内容,但它没有工作:

let request = NSMutableURLRequest(URL: url! )
request.HTTPMethod = "POST"
let postString = "appId=myId9&appKey=myKey&queries={item_name=burger&brand_name=McDonalds}"
request.HTTPBody = postString.dataUsingEncoding(NSUTF8StringEncoding)

3 个答案:

答案 0 :(得分:1)

你试过Alamofire吗?这很容易做到这一点。 你所要做的就是做类似下面的事情并发帖;

    let myParams = [
        "key1":  value1 ,
        "key2":  value2,
        "key3":  value3,
        "Key4":  value4
    ]


    Alamofire.request(.POST, posturl, parameters: myParams, encoding: .JSON)
        .authenticate(user: self.postUser, password: self.postPass)
        .validate(statusCode: 200..<300)
        .responseString { response in
            print("Response String: \(response.result.value)")
            if response.result.value != nil{
                let rJ = response.result.value!
                print("Response: " + rJ)
            }else
            {
                print("Fail")

            }

    }

希望这会有所帮助。 Alamofire也让我们更轻松。

答案 1 :(得分:1)

服务器期望什么内容类型?

您在第一部分显示application/json,但在第二部分显示application/x-www-form-urlencoded

如果您需要application/json,那么

let request = NSMutableURLRequest(URL: url!)
request.HTTPMethod = "POST"
request.addValue("application/json", forHTTPHeaderField: "Content-Type")
let postString = "{\"appId\":\"myId\", \"appKey\":\"myKey\", \"queries\":{\"item_name\":\"Kids Fries\", \"brand_name\":\"McDonalds\"}}"
request.HTTPBody = postString.dataUsingEncoding(NSUTF8StringEncoding)

如果你真的需要application/x-www-form-urlencoded,那么就会涉及一些猜测。为什么不尝试使用点语法。

let request = NSMutableURLRequest(URL: url!)
request.HTTPMethod = "POST"
request.addValue("application/x-www-form-urlencoded", forHTTPHeaderField: "Content-Type")
let postString = "appId=myId&appKey=myKey&queries.item_name=burger&queries.brand_name=McDonalds"
request.HTTPBody = postString.dataUsingEncoding(NSUTF8StringEncoding)

答案 2 :(得分:1)

您也可以使用Alamofire

尝试此代码
let parameters = [“Username”:”name”]

        let headers = ["Content-Type":"application/json"]

        Alamofire.request(.POST, “your URL here”, parameters: parameters, encoding: .JSON, headers: headers)
            .responseJSON { response in
                print("Response JSON: \(response.result.value)")
                //--------------------
                switch response.result {
                case .Success:
                    self.successGetData(response.result.value!)
                case .Failure(let error):
                    self.failedGetData()
                    print(error)
                }
            }