我是新手,所以我的代码可能会出现很多错误,但是我要实现的目标是将GET请求发送到带有 参数的localhost服务器。鉴于我的函数有两个参数,我试图做到更多baseURL:string,params:NSDictionary。我不确定如何将两者结合到实际的URLRequest中?到目前为止,这是我尝试过的
localhost
baseURL:string,params:NSDictionary
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上。要构建网址(并正确地将其转义), 您还可以使用URLComponents.
GET
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请求中具有特殊含义,实际上不应未经转义地传递。
application/x-www-form-urlencoded
苹果公司承认我们必须对+字符进行转义,但 建议我们手动进行:
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建议您的查询是否可以包含+字符并且您拥有将其解释为空格的服务器的建议。
因此,将其与sendRequest例行程序结合在一起,最终会得到 如下结果:
sendRequest
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 else { // was there no error, otherwise ... completion(nil, error) return } let responseObject = (try? JSONSerialization.jsonObject(with: data)) as? [String: Any] completion(responseObject, nil) } task.resume() }
And you’d call it like:
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中的基本思想。