带参数的 Swift GET 请求 [英] Swift GET request with parameters

查看:46
本文介绍了带参数的 Swift GET 请求的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我对 swift 很陌生,所以我的代码中可能会有很多错误,但我想要实现的是向带有参数的本地主机服务器发送一个 GET 请求.更重要的是,鉴于我的函数采用两个参数 baseURL:string,params:NSDictionary,我正试图实现它.我不确定如何将这两者结合到实际的 URLRequest 中?这是我迄今为止尝试过的

I'm very new to swift, so I will probably have a lot of faults in my code but what I'm trying to achieve is send a GET request to a localhost server with paramters. More so I'm trying to achieve it given my function take two parameters baseURL:string,params:NSDictionary. I am not sure how to combine those two into the actual URLRequest ? Here is what I have tried so far

    func sendRequest(url:String,params:NSDictionary){
       let urls: NSURL! = NSURL(string:url)
       var request = NSMutableURLRequest(URL:urls)
       request.HTTPMethod = "GET"
       var data:NSData! =  NSKeyedArchiver.archivedDataWithRootObject(params)
       request.HTTPBody = data
       println(request)
       var session = NSURLSession.sharedSession()
       var task = session.dataTaskWithRequest(request, completionHandler:loadedData)
       task.resume()

    }

}

func loadedData(data:NSData!,response:NSURLResponse!,err:NSError!){
    if(err != nil){
        println(err?.description)
    }else{
        var jsonResult: NSDictionary = NSJSONSerialization.JSONObjectWithData(data, options: NSJSONReadingOptions.MutableContainers, error: nil) as NSDictionary
        println(jsonResult)

    }

}

推荐答案

在构建 GET 请求时,请求没有正文,而是所有内容都在 URL 上进行.要构建 URL(并正确地对其进行百分比转义),您还可以使用 URLComponents.

When building a GET request, there is no body to the request, but rather everything goes on the URL. To build a URL (and properly percent escaping it), you can also use URLComponents.

var url = URLComponents(string: "https://www.google.com/search/")!

url.queryItems = [
    URLQueryItem(name: "q", value: "War & Peace")
]

唯一的技巧是大多数 Web 服务需要转义 + 字符百分比(因为它们会将其解释为 application/x-www-form-urlencoded 规范).但是 URLComponents 不会百分百转义它.Apple 认为 + 是查询中的有效字符,因此不应转义.从技术上讲,它们是正确的,它在 URI 的查询中是允许的,但它在 application/x-www-form-urlencoded 请求中具有特殊含义,并且真的不应该不转义地传递.

The only trick is that most web services need + character percent escaped (because they'll interpret that as a space character as dictated by the application/x-www-form-urlencoded specification). But URLComponents will not percent escape it. Apple contends that + is a valid character in a query and therefore shouldn't be escaped. Technically, they are correct, that it is allowed in a query of a URI, but it has a special meaning in application/x-www-form-urlencoded requests and really should not be passed unescaped.

Apple 承认我们必须对 + 字符进行百分比转义,但建议我们手动进行:

Apple acknowledges that we have to percent escaping the + characters, but advises that we do it manually:

var url = URLComponents(string: "https://www.wolframalpha.com/input/")!

url.queryItems = [
    URLQueryItem(name: "i", value: "1+2")
]

url.percentEncodedQuery = url.percentEncodedQuery?.replacingOccurrences(of: "+", with: "%2B")

这是一种不雅的解决方法,但它有效,如果您的查询可能包含 + 字符并且您有一个将它们解释为空格的服务器,Apple 会建议这样做.

This is an inelegant work-around, but it works, and is what Apple advises if your queries may include a + character and you have a server that interprets them as spaces.

因此,将其与您的 sendRequest 例程相结合,您最终会得到如下结果:

So, combining that with your sendRequest routine, you end up with something like:

func sendRequest(_ url: String, parameters: [String: String], completion: @escaping ([String: Any]?, Error?) -> Void) {
    var components = URLComponents(string: url)!
    components.queryItems = parameters.map { (key, value) in 
        URLQueryItem(name: key, value: value) 
    }
    components.percentEncodedQuery = components.percentEncodedQuery?.replacingOccurrences(of: "+", with: "%2B")
    let request = URLRequest(url: components.url!)
    
    let task = URLSession.shared.dataTask(with: request) { data, response, error in
        guard
            let data = data,                              // is there data
            let response = response as? HTTPURLResponse,  // is there HTTP response
            200 ..< 300 ~= response.statusCode,           // is statusCode 2XX
            error == nil                                  // was there no error
        else {
            completion(nil, error)
            return
        }
        
        let responseObject = (try? JSONSerialization.jsonObject(with: data)) as? [String: Any]
        completion(responseObject, nil)
    }
    task.resume()
}

你会这样称呼它:

sendRequest("someurl", parameters: ["foo": "bar"]) { responseObject, error in
    guard let responseObject = responseObject, error == nil else {
        print(error ?? "Unknown error")
        return
    }

    // use `responseObject` here
}

就我个人而言,我现在会使用 JSONDecoder 并返回一个自定义的 struct 而不是字典,但这在这里并不重要.希望这说明了如何将参数百分比编码到 GET 请求的 URL 中的基本思想.

Personally, I'd use JSONDecoder nowadays and return a custom struct rather than a dictionary, but that's not really relevant here. Hopefully this illustrates the basic idea of how to percent encode the parameters into the URL of a GET request.

请参阅此答案的先前修订版,了解 Swift 2 和手动百分比转义格式.

See previous revision of this answer for Swift 2 and manual percent escaping renditions.

这篇关于带参数的 Swift GET 请求的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆