将发布变量发送到iOS表单

时间:2013-06-03 13:29:01

标签: iphone ios objective-c

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

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

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

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

1 个答案:

答案 0 :(得分: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.
}