使用带参数的 POST 请求获得 JSON 结果

Get JSON Results with POST Request with Parameters

如何使用带参数的 POST 请求来获取 JSON?我知道如何通过简单的 GET 请求来完成。请求url为http://gyminyapp.azurewebsites.net/api/Gym,参数查询为

{
  "SearchCircle": {
    "Center": {
      "Latitude": 0,
      "Longitude": 0
    },
    "Radius": 0
  },
  "City": "string",
  "ZipCode": 0,
  "Type": "string"
}

我只想使用它的搜索圈部分,这意味着我可以忽略城市和邮政编码字段。我需要提供从当前用户位置获取的 Latitude/Longitude。我还需要将类型设置为 "radius"。

对于使用 GET 版本的简单 GET 请求,我这样做了。

let url = NSURL(string: "http://gyminyapp.azurewebsites.net/api/Gym")
        let data = NSData(contentsOfURL: url!)
        do {
            let json = try NSJSONSerialization.JSONObjectWithData(data!, options: NSJSONReadingOptions.MutableContainers)
            for gym in json as! [AnyObject] {
                gyms.append(gym)
            }
        } catch {
            print("Error")
        }

我就是这样做的。只需从参数中创建一个 NSDictionary 并转换为 NSData,我将其称为 postData。然后像往常一样,将 postData 作为 requestBody

发送
        let parameters = [
            "SearchCircle": 
               [ "Center" : 
                  ["Latitude" : 0, 
                   "Longitude" : 0] ]
            "Radius" : 0, 
            "City" : "", ...
            ... and so on


            ]            ]
        do
        {
            let postData = try NSJSONSerialization.dataWithJSONObject(parameters, options: .PrettyPrinted)

            let request = NSMutableURLRequest(URL: NSURL(string: "http...")!,
                                              cachePolicy: .UseProtocolCachePolicy,
                                              timeoutInterval: 10.0)
            request.HTTPMethod = "POST"

            request.HTTPBody = postData

            let session = NSURLSession.sharedSession()
            let dataTask = session.dataTaskWithRequest(request, completionHandler: { (data, response, error) -> Void in
                if (error != nil) {
                    print(error)
                } else {
                    let httpResponse = response as? NSHTTPURLResponse
                    print(httpResponse)
                    do {
                        // JSON serialization
                        self.dictionary = try NSJSONSerialization.JSONObjectWithData(data!, options: NSJSONReadingOptions()) as! NSDictionary
                        // if any data
                    }
                    catch {

                    }
                }
            })

            dataTask.resume()
        }
        catch {

        }

这是一个有效的代码,您只需输入请求参数的值即可。

let session = NSURLSession.sharedSession()
    let url = "http://gyminyapp.azurewebsites.net/api/Gym"
    let request = NSMutableURLRequest(URL: NSURL(string: url)!)
    request.HTTPMethod = "POST"
    request.addValue("application/json", forHTTPHeaderField: "Content-Type")
    let params:[String: AnyObject] = ["Type" : "string","SearchCircle" : ["Radius" : 0, "Center" : ["Latitude" : 0, "Longitude" : 0]]]
    do{
        request.HTTPBody = try NSJSONSerialization.dataWithJSONObject(params, options: NSJSONWritingOptions())
        let task = session.dataTaskWithRequest(request, completionHandler: {(data, response, error) in
            if let response = response {
                let nsHTTPResponse = response as! NSHTTPURLResponse
                let statusCode = nsHTTPResponse.statusCode
                print ("status code = \(statusCode)")
            }
            if let error = error {
                print ("\(error)")
            }
            if let data = data {
                do{
                let jsonResponse = try NSJSONSerialization.JSONObjectWithData(data, options: NSJSONReadingOptions())
                print ("data = \(jsonResponse)")
                }catch _ {
                    print ("OOps not good JSON formatted response")
                }
            }
        })
        task.resume()
    }catch _ {
        print ("Oops something happened buddy")
    }

然后在 if let data = data 中您需要解析响应。我检查了响应,它是 JSON 格式的数组。

这是为 Swift 4:

更新的已接受答案的代码
    let url = "http://gyminyapp.azurewebsites.net/api/Gym"
    let session = URLSession.shared
    let request = NSMutableURLRequest(url: URL(string: url))

    request.httpMethod = "POST"
    request.addValue("application/json", forHTTPHeaderField: "Content-Type")
    let params:[String: AnyObject] = ["Type" : "string",
                                      "SearchCircle" : ["Radius" : 0, "Center" : ["Latitude" : 0, "Longitude" : 0]]]
    do{
      request.httpBody = try JSONSerialization.data(withJSONObject: parameters, options: JSONSerialization.WritingOptions())
      let task = session.dataTask(with: request as URLRequest, completionHandler: {(data, response, error) in
        if let response = response {
          let nsHTTPResponse = response as! HTTPURLResponse
          let statusCode = nsHTTPResponse.statusCode
          print ("status code = \(statusCode)")
        }
        if let error = error {
          print ("\(error)")
        }
        if let data = data {
          do{
            let jsonResponse = try JSONSerialization.jsonObject(with: data, options: JSONSerialization.ReadingOptions())
            print ("data = \(jsonResponse)")
          }catch _ {
            print ("OOps not good JSON formatted response")
          }
        }
      })
      task.resume()
    }catch _ {
      print ("Oops something happened buddy")
    }
  }