由于 http post 请求中的 '&' 字符,字符串参数被分割

String parameter being divided because of '&' character on http post request

我的字符串参数被分割,因为包含“&”和“=”字符。我认为唯一的解决方案是使用 stringByReplacingOccurrencesOfString 替换这些字符并在我的服务器中执行相反的操作,但我认为这不是最佳解决方案。

我的参数是 url: "https://fbcdn-profile-a.akamaihd.net/hprofile-ak-xft1/v/t1.0-1/p200x200/10407385_1036550749695345_6853981176259794158_n.jpg?oh=ab150587befc541e8e3419b2fa245333&oe=56985B8D&gda=1456547848_432c041c647a7b3fd01f0adb33183aab"

我的代码:

let url : NSString = "http://domain.com/test/service/signInUp?name=\(name)&email=\(email)&facebookID=\(facebookID)&photo=\(photo)"

            let urlStr : NSString = url.stringByAddingPercentEscapesUsingEncoding(NSUTF8StringEncoding)!
            let searchURL : NSURL = NSURL(string: urlStr as String)!

            let request = NSMutableURLRequest(URL: searchURL)
            request.HTTPMethod = "POST"

            var response: NSURLResponse?

            var urlData: NSData?

            do {
                urlData = try NSURLConnection.sendSynchronousRequest(request, returningResponse: &response)

当您在查询字符串中包含 URL 时,包含的 URL 参数中的查询字符串将仅被视为外部 URL 查询字符串的一部分,并且所以事情变得一团糟(技术术语)。

解决方案是在将 URL 参数放入 URL 之前对其进行百分比编码,但您不能使用 stringByAddingPercentEncoding,因为此函数不对 & 字符进行编码导致您出现问题的原因。

可以使用stringByAddingPercentEncodingWithAllowedCharacters()

let encodedPhone = photo.stringByAddingPercentEncodingWithAllowedCharacters(NSCharacterSet.alphanumericCharacterSet());

let url : NSString = "http://domain.com/test/service/signInUp?name=\(name)&email=\(email)&facebookID=\(facebookID)&photo=\(encodedPhoto!)"

如果服务器没有自动为您执行此操作,您可能需要在服务器上对该参数进行百分比解码