0

以前,我在将特殊字符发布到 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 ?

感谢您的协助。

4

1 回答 1

0

发布此问题后,我尝试再次执行此操作。

以前,我使用过别人编写的 Web 服务。我怀疑它与一些自定义转义字符功能有关。

这一次,我编写了自己的 Web 服务,并且运行良好。我什至不需要使用“NSString_URLEncoding”

于 2013-11-01T08:35:51.747 回答