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

时间:2016-05-30 12:48:31

标签: json swift http-post nsurlsession nsurlrequest

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

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

我想要使用此搜索圈部分,这意味着我可以忽略City和ZipCode字段。我需要提供从当前用户位置获取的纬度/经度。我还需要将Type设置为" 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")
        }

3 个答案:

答案 0 :(得分:3)

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

Command

然后在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") } 中你需要解析响应。我检查了响应,它是JSON格式的数组。

答案 1 :(得分:0)

这就是我做的。只需使用params 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 {

        }

答案 2 :(得分:0)

这是为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")
    }
  }