gpt4 book ai didi

ios - xcode 使用 json 和 POST 来验证用户名和密码

转载 作者:行者123 更新时间:2023-11-29 02:31:21 24 4
gpt4 key购买 nike

我是 POST 的新手,刚刚编写了一段代码,该代码采用输入的用户名和密码并通过 POST 发送以进行验证。如果有效,则返回 true,否则返回 false。我认为我的代码大部分都能正常工作,但我的返回数据中肯定缺少某些东西,因为它不输出真或假。这是我的代码:

- (IBAction)btnLogIn:(id)sender;
{
//getting the username and password and putting it into a string
NSString *post =[[NSString alloc] initWithFormat:@"username= %@ &password =%@",[self.lblUserName text],[self.lblPassword text]];

//output the string
NSLog(@"PostData: %@",post);

//setting the URL to post to
NSURL *url=[NSURL URLWithString:@"myurl.php"];

//converts string to data that can be used to post
NSData *postData = [post dataUsingEncoding:NSASCIIStringEncoding allowLossyConversion:YES];


//get the length of the string
NSString *postLength = [NSString stringWithFormat:@"%lu", (unsigned long)[postData length]];

//formatting the URL
NSMutableURLRequest *request = [[NSMutableURLRequest alloc] init] ;
[request setURL:url];
[request setHTTPMethod:@"POST"];
[request setValue:postLength forHTTPHeaderField:@"Content-Length"];
[request setValue:@"application/json" forHTTPHeaderField:@"Accept"];
[request setValue:@"application/x-www-form-urlencoded" forHTTPHeaderField:@"Content-Type"];
[request setHTTPBody:postData];

NSURLResponse *requestResponse;
NSData *requestHandler = [NSURLConnection sendSynchronousRequest:request returningResponse:&requestResponse error:nil];

NSString *requestReply = [[NSString alloc] initWithBytes:[requestHandler bytes] length:[requestHandler length] encoding:NSASCIIStringEncoding];
NSLog(@"requestReply: %@", requestReply);

我不确定哪部分缺失或错误。一切运行良好,只是在我测试时返回空白。

最佳答案

这是另一种方法

  //Create the request

NSMutableURLRequest *request = [[NSMutableURLRequest alloc] initWithURL:[NSURL URLWithString:@"myurl.php"]];
// create the Method "GET" or "POST"

[request setHTTPMethod:@"POST"];

//Pass The String to server
NSString *userUpdate =[NSString stringWithFormat:@"username=%@&password=%@",[self.lblUserName text],[self.lblPassword text],nil];

//Check The Value what we passed
NSLog(@"the data Details is =%@", userUpdate);

//Convert the String to Data
NSData *data1 = [userUpdate dataUsingEncoding:NSUTF8StringEncoding];

//Apply the data to the body
[request setHTTPBody:data1];

//Create the response and Error

NSError *err;
NSURLResponse *response;

NSData *responseData = [NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&err];

NSString *resSrt = [[NSString alloc]initWithData:responseData encoding:NSASCIIStringEncoding];

//This is for Response
NSLog(@"got response==%@", resSrt);

if(resSrt)
{
NSLog(@"got response");


}
else
{
NSLog(@"faield to connect");
}

关于ios - xcode 使用 json 和 POST 来验证用户名和密码,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26835881/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com