如何在Swift中转义HTTP参数 [英] How to escape the HTTP params in Swift

查看:430
本文介绍了如何在Swift中转义HTTP参数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试向HTTP服务器发帖

I'm trying to make a post to an HTTP server

顺便说一下这是我的代码:

By the way this is my code:

  func sendPostToUrl(url:String, withParams params: [String: String?] ) {
    var request = NSMutableURLRequest(URL: NSURL(string: url)!)
    var session = NSURLSession.sharedSession()
    request.HTTPMethod = "POST"

    var err: NSError?
    var bodyData = ""
    for (key,value) in params{
        if (value==nil){ continue }
        let scapedKey = key.stringByAddingPercentEncodingWithAllowedCharacters(
                 .URLHostAllowedCharacterSet())!
        let scapedValue = value!.stringByAddingPercentEncodingWithAllowedCharacters(
                .URLHostAllowedCharacterSet())!
        bodyData += "\(scapedKey)=\(scapedValue)&"
    }
    request.HTTPBody = bodyData.dataUsingEncoding
               (NSUTF8StringEncoding, allowLossyConversion: true)

    var task = session.dataTaskWithRequest(request, 
    completionHandler: {data, response, error -> Void in
        println("Response: \(response)")
        let dataString = NSString(data: data, encoding: NSUTF8StringEncoding)
        println("Data: \(dataString)")

    })
    task.resume()
}

它有效但不完美。如果我以这种方式调用函数:

It works but is not perfect. If I call the function this way:

    client.sendPostToUrl("http://novagecko.com/tests/test.php", 
        withParams: ["hello":"world","inject":"param1=value1&param2=value2"]);

服务器检测到3个帖子字段(密钥 hello inject param2 )而不是2。

The server detects 3 post fields (with keys hello,inject and param2) instead of 2.

如何逃避键和值?

我还能做些什么改进方法吗?

Is there something more I could do for improving the method?

推荐答案

如果您可以定位iOS 8(感谢@Rob),请使用 NSURLComponents 来转义参数:

If you can target iOS 8 (thanks @Rob), use NSURLComponents to escape your parameters instead:

import Foundation

func encodeParameters(#params: [String: String]) -> String {
    var queryItems = map(params) { NSURLQueryItem(name:$0, value:$1)}
    var components = NSURLComponents()
    components.queryItems = queryItems
    return components.percentEncodedQuery ?? ""
}

现在 encodeParameters(params:[你好] :world,inject:param1 = value1& param2 = value2])返回 hello = world& inject = param1%3Dvalue1%26param2%3Dvalue2 正如您所期望的那样。

Now encodeParameters(params:["hello":"world","inject":"param1=value1&param2=value2"]) returns hello=world&inject=param1%3Dvalue1%26param2%3Dvalue2 as you would expect.

否则,创建可让您正确转义值的字符集的最佳方法是:

Otherwise, the best way to create the character set that will let you escape your values properly is this:

var safeCharacterSet = NSCharacterSet.URLQueryAllowedCharacterSet().mutableCopy()
safeCharacterSet.removeCharactersInString("&=")

并查看@ rintaro的答案,正确使用filter / map以良好的方式执行编码。

and see @rintaro's answer to use filter/map properly to perform the encoding in a nice way.

这篇关于如何在Swift中转义HTTP参数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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