user1506704
user1506704

Reputation: 23

Bad URL Error With NSURLRequest

I have a NSURLRequest created next way:

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;

The result string is http://myserveradress.ru/api/users/register?register_password=password&register_password_confirm=password&[email protected]&register_terms=1&register_user=myname&process_registration=1&register_name=Artem%Kulikov and the error states

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

In browser the link works fine. The problem is only in the app.

Upvotes: 0

Views: 5418

Answers (2)

Michael Boselowitz
Michael Boselowitz

Reputation: 3006

That is not the proper way to escape the strings, there is a method for that, stringByAddingPercentEscapesUsingEncoding:. So change it to:

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]];

Not to mention the proper escape code for a space is %20 not %.

Upvotes: 14

Deepesh
Deepesh

Reputation: 8053

@user1506704, you are not use encoding method like in register_name, Are there spaces or other special characters in the register_name? Use NSString method stringByAddingPercentEscapesUsingEncoding:.

You can try and escape the URL:

- (NSString *)stringByAddingPercentEscapesUsingEncoding:(NSStringEncoding)encoding` 

Upvotes: 2

Related Questions