Sending data with POST, issue with character encod

2019-08-13 15:11发布

问题:

I am having issues with my NSURLRequest and doing a POST whenever the string includes %, for example.

On my website, I can see that the encoding is ISO-8859-1,utf-8 for Accept-Charset but for some reason I cannot get the POST to work if it includes "%&$" etc. It seems like it won't encode it with UTF-8 encoding. Am I doing something wrong in the below code?

NSData *postData = [credentials dataUsingEncoding:NSUTF8StringEncoding allowLossyConversion:NO];
NSString *postLength = [NSString stringWithFormat:@"%d", [postData length]];
NSMutableURLRequest *request = [[[NSMutableURLRequest alloc] init] autorelease];
[request setURL:[NSURL URLWithString:@"http://www.website.com/login.php"]];
[request setHTTPMethod:@"POST"];
[request setValue:postLength forHTTPHeaderField:@"Content-Length"];
[request setValue:@"application/x-www-form-urlencoded" forHTTPHeaderField:@"Content-Type"];
[request setHTTPBody:postData];

回答1:

You may want to hear "Content-Transfer-Encoding".

Content-Type: text/plain; charset=UTF-8

Content-Transfer-Encoding: binary

or if you have problems specially with those chars

Content-Transfer-Encoding: base64

EDIT: The "application/x-www-form-urlencoded" makes the "%" signs happen.