【问题标题】:Get JSON Results with POST Request with Parameters使用带参数的 POST 请求获取 JSON 结果
【发布时间】:2016-05-30 12:48:31
【问题描述】:

如何使用带有参数的 POST 请求来获取 JSON?我知道如何用一个简单的 GET 请求来做到这一点。请求url为http://gyminyapp.azurewebsites.net/api/Gym,参数查询为

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

我只想使用其中的搜索圈部分,这意味着我可以忽略 City 和 ZipCode 字段。我需要提供从当前用户位置获取的纬度/经度。我还需要将类型设置为“半径”。

对于使用 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")
        }

【问题讨论】:

  • 如果它与 GET 一起使用,为什么要使用 POST?此外,如果您要检索数据,GET 是更合适的动词。
  • 在我的 API 中,GET 为我提供了数据库中的所有位置。这篇文章让我可以根据某些标准缩小结果范围。

标签: json swift http-post nsurlsession nsurlrequest


【解决方案1】:

这是一个工作代码,你只需要输入你的请求参数的值。

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 格式的数组。

【讨论】:

    【解决方案2】:

    我就是这样做的。只需从参数中创建一个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 {
    
            }
    

    【讨论】:

      【解决方案3】:

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

      【讨论】:

        猜你喜欢
        • 2016-08-07
        • 1970-01-01
        • 2019-02-07
        • 2018-02-18
        • 1970-01-01
        • 2019-01-11
        • 2019-12-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多