0

我有一个 NSURLRequest 创建下一个方式:

NSString *url=[NSString stringWithFormat:@"http://myserveradress.com/api/users/register?register_password=%@&register_password_confirm=%@&register_email=%@&register_terms=1&register_user=%@&process_registration=1&register_name=%@"
                   ,
                   [password stringByReplacingOccurrencesOfString:@" " withString:@"%"],[confirm stringByReplacingOccurrencesOfString:@" " withString:@"%"],[email stringByReplacingOccurrencesOfString:@" " withString:@"%"],[user stringByReplacingOccurrencesOfString:@" " withString:@"%"],[realName stringByReplacingOccurrencesOfString:@" " withString:@"%"]
                   ];
    NSURLRequest *request=[NSURLRequest requestWithURL:[NSURL URLWithString:url]];
    NSError *error;
    NSData *data=[NSURLConnection sendSynchronousRequest:request returningResponse:nil error:&error];
    NSString *result_string = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
    return result_string;

结果字符串是http://myserveradress.ru/api/users/register?register_password=password&register_password_confirm=password&register_email=myname@mail.com&register_terms=1&register_user=myname&process_registration=1&register_name=Artem%Kulikov并且错误状态

Error Domain=NSURLErrorDomain Code=-1000 "bad URL" UserInfo=0x71e62b0 {NSUnderlyingError=0x71e6470 "bad URL", NSLocalizedDescription=bad URL}

在浏览器中,链接工作正常。问题仅在应用程序中。

4

2 回答 2

14

这不是逃避字符串的正确方法,有一种方法,stringByAddingPercentEscapesUsingEncoding:. 所以改成:

NSString *url = [NSString stringWithFormat:@"http://myserveradress.com/api/users/register?register_password=%@&register_password_confirm=%@&register_email=%@&register_terms=1&register_user=%@&process_registration=1&register_name=%@"
                   , password, confirm, email, user, realName];
NSString *properlyEscapedURL = [url stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
NSURLRequest *request=[NSURLRequest requestWithURL:[NSURL URLWithString:properlyEscapedURL]];

更不用说空格的正确转义码%20不是%.

于 2012-07-06T12:36:54.250 回答
2

@user1506704,您没有使用 register_name 中的编码方法,register_name 中是否有空格或其他特殊字符?使用NSString方法 stringByAddingPercentEscapesUsingEncoding:.

您可以尝试转义 URL:

- (NSString *)stringByAddingPercentEscapesUsingEncoding:(NSStringEncoding)encoding` 
于 2012-07-06T12:34:24.073 回答