使用HTTP-Post:iPhone登录

使用HTTP-Post:iPhone登录,iphone,cocoa-touch,login,http-post,Iphone,Cocoa Touch,Login,Http Post,我已经创建了一个登录视图。每次我登录时,即使我输入了正确的凭据,也会出现登录失败错误。这就是我现在使用的方法: NSString *postString = [[NSString alloc] initWithFormat:@"username=%@&password=%@",userName, password]; // Package the string in an NSData object NSData *requestData = [postString da

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

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];

你能核实一下答复是什么吗?此外,您可能应该对发布的参数进行编码:

ASIHttpRequest示例
响应是HTML格式的。当我看到HTML代码时,它显示了登录失败页面的代码。如果是这样的话,我猜你是服务器端出现了问题。您应该在服务器端验证它是否收到了预期发送的用户名和密码。另外,我应该提到,已经有一个非常好的类库用于发出HTTP请求。这对我来说是个救命恩人:我不知道如何使用AsitpRequest(我已经更新了我的答案。请按照此处ASIHttpRequest的设置说明进行操作:非常有用如果您不想在项目中包含单独的库,只需使用原始代码并将用户名更改为[username stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding],当您将它们添加到第一行中的数据时,密码也类似。
- (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
}