简体   繁体   English

将&符号转换为UTF 8

[英]convert ampersand character to utf 8

I send post request with data to my server: 我将带有数据的发布请求发送到服务器:

var syncData = "data=Hello&World"
let urlRequest = NSMutableURLRequest(URL: NSURL(string: url)!, cachePolicy:  NSURLRequestCachePolicy.ReloadIgnoringCacheData, timeoutInterval: NSTimeInterval(60))

urlRequest.HTTPMethod = "POST"
urlRequest.HTTPBody = syncData.dataUsingEncoding(NSUTF8StringEncoding)

But problem that server can't decode &(ampersand) character. 但是服务器无法解码&(ampersand)字符的问题。 On server i get only word "Hello". 在服务器上,我仅收到单词“ Hello”。 And it is not the server issue. 这不是服务器问题。 because i tried to sent this string with java and python and curl. 因为我尝试使用java和python和curl发送此字符串。
All works good. 一切正常。

I tried this: NSXMLParser problem with "&"(Ampersand) character 我试过了: NSXMLParser问题,带有“&”(Ampersand)字符

but it doesn't help... Any ideas ? 但这无济于事...有什么想法吗?

As Musa said. 正如穆萨所说。 Solution will be: 解决方案将是:

let customAllowedSet =  NSCharacterSet(charactersInString:"=\"#%/<>?@\\^`{|}&").invertedSet
    syncData = syncData.stringByAddingPercentEncodingWithAllowedCharacters(customAllowedSet)!

    urlRequest.HTTPBody = syncData.dataUsingEncoding(NSUTF8StringEncoding)

try 尝试

var sync = syncData.stringByReplacingOccurrencesOfString("&", withString: " ")
urlRequest.HTTPBody = sync.dataUsingEncoding(NSUTF8StringEncoding)

place the sync variable under the syncData variable and replace your urlRequest with the one above using the new sync variable 将sync变量放置在syncData变量下,并使用新的sync变量将您的urlRequest替换为上面的一个

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM