0

我正在尝试将用户名和密码发送到通常通过表单完成的网站。然而,服务器将我重定向到登录页面,这通常发生在用户名和密码错误的情况下。用户名是电子邮件地址的形式,密码是字符串。

我目前确实可以访问该网站,因为开发人员正在检查这些值是否得到正确处理。任何人都可以在下面创建的代码中看到任何明显的错误吗?

请注意,出于隐私原因,我已从示例代码中删除了 URL。

// 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;
}
4

1 回答 1

3

此字符串不正确NSString *post = @"username=example1%40example.com&example2"; 在&符号之后,您必须提供 key=value。
@"key1=value1&key2=value2";

工作代码示例:

在 .h 文件集委托中:

@interface Controller <NSURLConnectionDataDelegate>

在 .m 文件中:

- (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.
}
于 2013-06-03T13:32:09.510 回答