开发者

NSMutableUrlRequest eats plus signs

I create NSMutableUrlRequest for sending data to server, add all necessary fields to it and then add the string for sending like this:

[theRequest setHTTPBody:[postString dataUsingEncoding: NSUTF8StringEncoding]];

postString is a usual NSString.

The problem is, when I receive this request at the server, all the plus (+) signs disappear from the http body. So if I had "abcde+fghj" on iPhone, I get "abcde fghj" on the server".

Can this be some encoding problem from using dataUsingEncoding: NSUTF8StringEncoding? Or some NSMutableUrlRequest stripping feature? What开发者_StackOverflow社区 can I do to make it stop stripping plus signs? I need to receive UTF8 strings at the server side.


The plus (+) sign is a standard shortcut for a space, in a URL's query string portion. If you want a literal +, encode it as %2b.


May be the server doesn't know which is the encoding of the POST body. Have you tried to add the charset=UTF-8 into the header of your request like that:

[theRequest setValue:@"application/x-www-form-urlencoded; charset=UTF-8" forHTTPHeaderField:@"Content-Type"];


For e.g. you need to post data to the backend with a "Content-Type" -> "application/x-www-form-urlencoded"

application/x-www-form-urlencoded: the keys and values are encoded in key-value tuples separated by '&', with a '=' between the key and the value. Non-alphanumeric characters in both keys and values are percent encoded: this is the reason why this type is not suitable to use with binary data (use multipart/form-data instead)

Reference

You can percent-encode your data by applying function addingPercentEncoding to your string in Swift:

guard let jsonString = String(data: jsonData, encoding: .utf8)?.addingPercentEncoding(withAllowedCharacters: .alphanumerics) else {
   failureCompletion()
   return
}

var request = URLRequest(url: url)
...
request.setValue("application/x-www-form-urlencoded", forHTTPHeaderField: "Content-Type")
request.httpBody = "jsonString".data(using: .utf8)
...
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜