使用HTTP Post登录:iPhone

时间:2010-12-14 15:57:42

标签: iphone cocoa-touch login http-post

我已经创建了一个Login视图。每次我登录它都会给我登录失败错误,即使我输入正确的凭据。这是我现在使用的方法:

NSString *postString = [[NSString alloc] initWithFormat:@"username=%@&password=%@",userName, password];
    // Package the string in an NSData object
    NSData *requestData = [postString dataUsingEncoding:NSASCIIStringEncoding allowLossyConversion:YES];

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

    // Create the URL request
    NSMutableURLRequest *request = [[NSMutableURLRequest alloc] initWithURL: [NSURL URLWithString:@"https://172.168.1.9/dologin.php"]];  // create the URL request
    [request setHTTPMethod: @"POST"];   // you're sending POST data
    [request setHTTPBody: requestData];  // apply the post data to be sent
    [request setValue:postLength forHTTPHeaderField:@"Content-Length"];
    [request setValue:@"application/x-www-form-urlencoded" forHTTPHeaderField:@"Content-Type"];

    // Call the URL
    NSURLResponse *response;  // holds the response from the server
    NSError *error;   // holds any errors
    NSData *returnData = [NSURLConnection sendSynchronousRequest: request returningResponse:&response error:&error];

1 个答案:

答案 0 :(得分:2)

您能验证回复是什么吗?此外,您应该对您发布的参数进行编码:Objective-c iPhone percent encode a string?

ASIHttpRequest示例

- (void)btnLoginTap {
    [txtUsername resignFirstResponder];
    [txtPassword resignFirstResponder];

    NSURL *url = [[NSURL alloc] initWithString:YOUR_URL_HERE];
    ASIFormDataRequest *request = [ASIFormDataRequest requestWithURL:url];
    [request setTimeOutSeconds:120];
    [request setPostValue:txtUsername.text forKey:@"username"];
    [request setPostValue:txtPassword.text forKey:@"password"];
    [request setDelegate:self];
    [request startAsynchronous];
    [url release];

    //Show a loading view or something here while you wait for the response...
}

- (void) requestFinished:(ASIHTTPRequest *)request {
    //Hide your loading view here.
    NSString *responseString = [request responseString];
    DLog(@"%@", responseString);
    //Request succeeded
}

- (void) requestFailed:(ASIHTTPRequest *)request {
    //Hide your loading view here.
    NSError *error = [request error];
    DLog(@"%@", [error localizedDescription]);
    //Request failed
}