简体   繁体   中英

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. On server i get only word "Hello". And it is not the server issue. because i tried to sent this string with java and python and curl.
All works good.

I tried this: NSXMLParser problem with "&"(Ampersand) character

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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