NSMutableUrlRequest eats plus signs

I create an NSMutableUrlRequest to send data to the server, add all the necessary fields to it, and then add the line to send as follows:

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

postString is a regular NSString.

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

Could this be a coding problem when using dataUsingEncoding: NSUTF8StringEncoding? Or any NSMutableUrlRequest disable function? What can I do to stop withdrawal plus signs? I need to get UTF8 strings on server side.

+5
source share
3 answers

The plus sign (+) is the standard label for the space in the query string part of the URL. If you need a literal +, encode it as% 2b.

+4
source

Maybe the server does not know what the encoding of the POST body is. You tried to add charset = UTF-8 to your request header as follows:

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

For example, you need to send data to the server with "Content-Type" -> "application/x-www-form-urlencoded"

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

Link

You can percent encode your data by applying the addingPercentEncoding function to your line 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
source

Source: https://habr.com/ru/post/1304752/


All Articles