3

目前我有一个要发布到 URL 的字符串。

除了遇到“&”和“?”等特殊字符外,它工作得非常好。它不会发布之后的任何数据。例如,如果我有一个字符串“I am something & something?”,它只会发布“I am something”。至于“?”,发布后将转换为“2”。

reason = 'What see see! Are you sure'2''

我很确定它一定与编码有关,因为我可以看到“我是什么东西?” 就像在我设置编码之前一样:

NSData *postData = [post dataUsingEncoding:NSASCIIStringEncoding];

我也尝试了以下编码但没有成功:

NSData *postData = [post dataUsingEncoding:NSUTF8StringEncoding];
NSData *postData = [post dataUsingEncoding:NSNonLossyASCIIStringEncoding];
NSData *postData = [post dataUsingEncoding:NSISOLatin1StringEncoding];

以下是我从 postData 开始的代码:

NSData *postData = [post dataUsingEncoding:NSASCIIStringEncoding];
    //NSLog(@"PostData: %@", postData);
    NSString *check = [[NSString alloc] initWithData:postData encoding:NSASCIIStringEncoding];
    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];
    NSString *strResponse = [[NSString alloc] initWithData:responseData encoding:NSUTF8StringEncoding];
     NSLog(@"Response: %@", strResponse);
     if(err!=nil) {
     NSLog(@"Error: %@", [err description]);
     }

请协助。感谢您的帮助。

4

1 回答 1

6

在某个地方可能有更好的答案,但是这个类扩展已经为我工作了一段时间。我通过查看一些帖子拼凑了 % 逃脱...

//  NSString+URLEncoding.h
@interface NSString (NSString_URLEncoding)

- (NSString *)urlEncodeUsingEncoding:(CFStringEncoding)encoding;
- (NSString *)urlEncode;

@end

//  NSString+URLEncoding.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];
}

然后在其他类中发送一个字符串......

// SomeOtherClass.m

#import "NSString+URLEncoding.h"

NSString *encodedString = [@"This & this? are 'challenging' to !% encode" urlEncode];
于 2013-08-15T04:07:09.570 回答