以前,我在将特殊字符发布到 Web 服务时遇到问题。但是现在,我可以发布除“?”之外的所有特殊字符。我不明白为什么。
NSString+URLEndoding.h
@interface NSString (NSString_URLEncoding) //originally NSOBject
- (NSString *)urlEncodeUsingEncoding:(CFStringEncoding)encoding;
- (NSString *)urlEncode;
@end
NSString+URLEndoding.m
@implementation NSString (NSString_URLEncoding)
- (NSString *)urlEncodeUsingEncoding:(CFStringEncoding)encoding {
return CFBridgingRelease(CFURLCreateStringByAddingPercentEscapes(kCFAllocatorDefault,
(__bridge CFStringRef)self,
NULL,
CFSTR("!*'();:@&=+$,/?%#[]"),
encoding));
}
- (NSString *)urlEncode {
return [self urlEncodeUsingEncoding:kCFStringEncodingUTF8];
}
@end
以下是 UpdateSomething.m 的一部分:
NSString *encodeSomething = [something urlEncode];
NSMutableString *post = [NSMutableString stringWithFormat:@"something=%@", encodeSomething];
//NSLog(@"post: %@", post);
NSData *postData = [post dataUsingEncoding:NSASCIIStringEncoding];
//NSLog(@"PostData: %@", postData);
NSString *check = [[NSString alloc] initWithData:postData encoding:NSASCIIStringEncoding]; //UTF8 also works.
NSLog(@"check string = %@", check);
NSString *postLength = [NSString stringWithFormat:@"%d", [postData length]];
NSMutableURLRequest *request = [[NSMutableURLRequest alloc] init];
[request setURL:[NSURL URLWithString:strURLQueryString]];
[request setHTTPMethod:@"POST"];
[request setValue:postLength forHTTPHeaderField:@"Content-Length"];
[request setHTTPBody:postData];
NSURLResponse *response;
NSError *err=nil;
NSData *responseData = [NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&err];
}
检查的输出是:
check string = something%20%3F
我知道“%3F”=“?”。但是我不明白为什么每次输入问号时都会出错。
Response: Input Array does not match ?
感谢您的协助。