我有下一个创建的NSURLRequest:
NSString *url=[NSString stringWithFormat:@"http://myserveradress.com/api/users/register?register_password=%@®ister_password_confirm=%@®ister_email=%@®ister_terms=1®ister_user=%@&process_registration=1®ister_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®ister_password_confirm=password®ister_email=myname@mail.com®ister_terms=1®ister_user=myname&process_registration=1®ister_name=Artem%Kulikov
,错误状态为
Error Domain=NSURLErrorDomain Code=-1000 "bad URL" UserInfo=0x71e62b0 {NSUnderlyingError=0x71e6470 "bad URL", NSLocalizedDescription=bad URL}
在浏览器中链接正常。问题仅在于应用程序。
答案 0 :(得分:14)
这不是逃避字符串的正确方法,有一种方法,stringByAddingPercentEscapesUsingEncoding:
。所以改成它:
NSString *url = [NSString stringWithFormat:@"http://myserveradress.com/api/users/register?register_password=%@®ister_password_confirm=%@®ister_email=%@®ister_terms=1®ister_user=%@&process_registration=1®ister_name=%@"
, password, confirm, email, user, realName];
NSString *properlyEscapedURL = [url stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
NSURLRequest *request=[NSURLRequest requestWithURL:[NSURL URLWithString:properlyEscapedURL]];
更不用说空格的正确转义码是%20
而不是%
。
答案 1 :(得分:2)
@ user1506704,你没有使用register_name中的编码方法,register_name中是否有空格或其他特殊字符?使用NSString
方法stringByAddingPercentEscapesUsingEncoding:.
您可以尝试转义网址:
- (NSString *)stringByAddingPercentEscapesUsingEncoding:(NSStringEncoding)encoding`