Question

I am trying to create an app that sends a password through POST to a php website, but I am having trouble with the PostData. When the password contains a & symbol it thinks that the variable will be split into two.

For example:

  • Username: testuser
  • Email: email@email.com
  • Password: Pass&word1

The following would be the PostData

username=testuser&email=email@email.com&password=Pass&word1
                                                     ^This breaks the password up

This is my code:

@try {

    NSString *post = [[NSString alloc] initWithFormat:@"username=%@&email=%@&password=%@", usernameField.text, emailField.text, password1Field.text];
    NSLog(@"PostData: %@",post);

    NSURL *url=[NSURL URLWithString:@"http://mywebsite.com/test/register.php"];

    NSData *postData = [post dataUsingEncoding:NSASCIIStringEncoding allowLossyConversion:YES];

    NSString *postLength = [NSString stringWithFormat:@"%lu", (unsigned long)[postData length]];

    NSMutableURLRequest *request = [[NSMutableURLRequest alloc] init];
    [request setURL:url];
    [request setHTTPMethod:@"POST"];
    [request setValue:postLength forHTTPHeaderField:@"Content-Length"];
    [request setValue:@"application/json" forHTTPHeaderField:@"Accept"];
    [request setValue:@"application/x-www-form-urlencoded" forHTTPHeaderField:@"Content-Type"];
    [request setHTTPBody:postData];
}
@catch (NSException *exception) {
    NSLog(@"Exception: %@", exception);
}

EDIT

I also just realized that letters like: àìú are causing problems as well.

Was it helpful?

Solution

Ampersands have special meaning in HTTP requests. You'll need to URL encode those parameters to make sure that the server software knows that they are data.

You'll need to do something like this for each parameter in the request string:

NSString* encodedPassword = (NSString *)CFURLCreateStringByAddingPercentEscapes(NULL,
           (CFStringRef)password1Field.text,
           NULL,
           (CFStringRef)@"!*'\"();:@&=+$,/?%#[]% ",
           CFStringConvertNSStringEncodingToEncoding(NSUTF8Encoding));

Take a look at this reference for a great example of adding your URL encoder to the NSString class: http://madebymany.com/blog/url-encoding-an-nsstring-on-ios

As for your edit, characters like àìú are probably giving you problems because you are using NSASCIIStringEncoding. Try NSUTF8StringEncoding as it supports a much larger range of potential characters than ASCII.

OTHER TIPS

Simple solution: Use '|' instead of '&' in your Objective C code.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top