NSMutableUrlRequest eats plus signs

浪尽此生 提交于 2020-01-01 11:56:27

问题


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 can I do to make it stop stripping plus signs? I need to receive UTF8 strings at the server side.


回答1:


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.




回答2:


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"];



回答3:


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)
...


来源:https://stackoverflow.com/questions/2491351/nsmutableurlrequest-eats-plus-signs

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!