samb90
samb90

Reputation: 1073

Sending post variables to iOS form

I am trying to send a username and password to a website which is normally done through a form. The server however is redirecting me to a login page, which usually occurs when the username and password is wrong. The username is in the form of an email address and the password is a string.

I do currently have access to the website as the developer is away to check that the values are being processed correctly. Can anyone see any obvious errors in the code I have created below?

Please note I have removed the URL from the example code for privacy reasons.

// Validate login
-(bool)validateLogin{

    // Initialize URL to be fetched
    NSURL *url = [NSURL URLWithString:@"removedurl"];

    NSString *post = @"username=example1%40example.com&password=example2";

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

    NSString *postLength = [NSString stringWithFormat:@"%d", [postData length]];

    // Initalize a request from a URL
    NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:[url standardizedURL]];

    //set url
    [request setURL:url];
    //set http method
    [request setHTTPMethod:@"POST"];
    //set request length
    [request setValue:postLength forHTTPHeaderField:@"Content-Length"];
    //set request content type we MUST set this value.
    [request setValue:@"application/x-www-form-urlencoded" forHTTPHeaderField:@"Content-Type"];
    //set post data of request
    [request setHTTPBody:postData];

    NSLog(@"%@", [request allHTTPHeaderFields]);

    //initialize a connection from request
    NSURLConnection *connection = [[NSURLConnection alloc] initWithRequest:request delegate:self];
    _connection = connection;    
    //start the connection
    [connection start];

    return YES;
}

Upvotes: 0

Views: 637

Answers (1)

pbibergal
pbibergal

Reputation: 2921

This string is not correct NSString *post = @"username=example1%40example.com&example2"; After ampersand you have to provide key=value.
@"key1=value1&key2=value2";

Example of working code:

In .h file set delegate:

@interface Controller <NSURLConnectionDataDelegate>

In .m file:

- (void)login {
    NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:urlString] cachePolicy:NSURLRequestUseProtocolCachePolicy timeoutInterval:kRequestTimeOut];
    request.HTTPMethod = @"POST";
    NSString *params = @"key1=value1&key2=value2";
    request.HTTPBody = [params dataUsingEncoding:NSUTF8StringEncoding];

    _data = [NSMutableData data];

    NSURLConnection *connection = [NSURLConnection connectionWithRequest:request delegate:self];
}

- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data {
    [_data appendData:data];
}

- (void)connectionDidFinishLoading:(NSURLConnection *)connection {
    //Parse your '_data' here.
}

Upvotes: 3

Related Questions