Recently I am converting my Python project to Objective-C. And I faced a problem when rewriting http request method in Objective-C. Here is the original Python implementation works perfectly:
data = {"username": username,"password": password}
status = requests.post("http://example.net/process.php",data=datas)
print(status.text)
if(status.text == "0"):
// Login Successfully
else:
// Login Failed
I attempt to make it works in Objective-C butkResponseData
has no value. Here is my Objective-C code:
NSURL *address = [[NSURL alloc] initWithString: @"http://example.net/process.php"];
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL: address];
[request setValue:@"application/json" forHTTPHeaderField:@"Accept"];
[request setValue:@"application/json" forHTTPHeaderField:@"Content-type"];
NSString *postString = [[NSString alloc] initWithFormat: @"{\"username\":\"%@\",\"password\":\"%@\"}", self.username, self.password];
NSData *postData = [postString dataUsingEncoding: NSUTF8StringEncoding];
request.HTTPMethod = @"POST";
request.HTTPBody = postData;
NSURLResponse *kResponse = nil;
NSError *error = nil;
NSData *kResponseData = [NSURLConnection sendSynchronousRequest: request returningResponse: &kResponse error: &error];
NSLog(@"%@\n", [[NSString alloc] initWithData: kResponseData encoding: NSUTF8StringEncoding], kResponseData);
if([[[NSString alloc] initWithData: kResponseData encoding: NSUTF8StringEncoding] isEqualToString: @"0"]){
// Login Successfully
}
else{
// Login Failed
}
And here is a part of server php:
$username = $_POST['username'];
$password = $_POST['password'];
$password = md5($password);
$sql = "SELECT * FROM USERS WHERE username = '$username'";
$result = mysqli_query($con,$sql);
if(mysqli_num_rows($result) == 0){
// User not found
echo '2';
exit();
}
while($row = mysqli_fetch_assoc($result)){
if($row['password'] == $password){
// Found user, password correct
echo '0';
exit();
}else{
// Incorrect password
echo '1';
exit();
}
}
So how can I get the login statement value in Objective-C likestatus.text
in Python?
Thanks for answering!
NSURLSession
Currently my code is here. Some are from another post of Stack OverFlow
NSError *error;
NSURLSessionConfiguration *configuration = [NSURLSessionConfiguration defaultSessionConfiguration];
NSURLSession *session = [NSURLSession sessionWithConfiguration: configuration delegate: self delegateQueue:nil];
NSURL *url = [NSURL URLWithString: @"http://example.net/process.php"];
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL: url cachePolicy: NSURLRequestUseProtocolCachePolicy timeoutInterval:60.0];
[request setValue:@"application/json" forHTTPHeaderField:@"Accept"];
[request setValue:@"text/html" forHTTPHeaderField:@"Content-type"];
// Also tries "application/json" but same issue
[request setHTTPMethod:@"POST"];
NSString *postString = [[NSString alloc] initWithFormat: @"{\"username\":\"%@\",\"password\":\"%@\"}", username, password];
NSData *postData = [postString dataUsingEncoding: NSUTF8StringEncoding];
[request setHTTPBody: postData];
NSURLSessionDataTask *postDataTask = [session dataTaskWithRequest:request completionHandler:^(NSData *data, NSURLResponse *kResponse, NSError *error) {
NSLog(@"%@", data);
NSLog(@"%@", kResponse);
NSLog(@"%@", error);
}];
[postDataTask resume];
I still got empty data.kResponse
anderror
also printed as follows:
2022-08-27 18:56:17.415 test[3699:46726] {length = 0, bytes = 0x}
2022-08-27 18:56:17.415 test[3699:46726] <NSHTTPURLResponse: 0x7ffaa5d002e0> { URL: http://example.net/process.php } { Status Code: 200, Headers {
"Cache-Control" = (
"no-store, no-cache, must-revalidate"
);
Connection = (
"keep-alive"
);
"Content-Encoding" = (
gzip
);
"Content-Type" = (
"text/html; charset=UTF-8"
);
Date = (
"Sat, 27 Aug 2022 10:56:17 GMT"
);
Expires = (
"Thu, 19 Nov 1981 08:52:00 GMT"
);
"Keep-Alive" = (
"timeout=4"
);
Pragma = (
"no-cache"
);
"Proxy-Connection" = (
"keep-alive"
);
Server = (
nginx
);
"Strict-Transport-Security" = (
"max-age=31536000"
);
"Transfer-Encoding" = (
Identity
);
Vary = (
"Accept-Encoding"
);
} }
2022-08-27 18:56:17.415 test[3699:46726] (null)
I also tried to initialize bothNSDictionary
andNSString
for params and then gopostData
:
// String method
NSString *postString = [[NSString alloc] initWithFormat: @"{\"username\":\"%@\",\"password\":\"%@\"}", self.username, self.password];
NSData *postData = [postString dataUsingEncoding: NSUTF8StringEncoding];
[request setHTTPBody: postData];
// Dictionary method
NSDictionary *postDictionary = [[NSDictionary alloc] initWithObjectsAndKeys: self.username ,@"username",self.password,@"password", nil];
NSData *postData = [NSJSONSerialization dataWithJSONObject: postDictionary options:0 error:nil];
[request setHTTPBody: postData];
Both two methods got {length = 0, bytes = 0x}. Is my problem setting up params wrongly or making not appropriate request?
Our community is visited by hundreds of web development professionals every day. Ask your question and get a quick answer for free.
Find the answer in similar questions on our website.
Do you know the answer to this question? Write a quick response to it. With your help, we will make our community stronger.
PHP (from the English Hypertext Preprocessor - hypertext preprocessor) is a scripting programming language for developing web applications. Supported by most hosting providers, it is one of the most popular tools for creating dynamic websites.
The PHP scripting language has gained wide popularity due to its processing speed, simplicity, cross-platform, functionality and distribution of source codes under its own license.
https://www.php.net/
DBMS is a database management system. It is designed to change, search, add and delete information in the database. There are many DBMSs designed for similar purposes with different features. One of the most popular is MySQL.
It is a software tool designed to work with relational SQL databases. It is easy to learn even for site owners who are not professional programmers or administrators. MySQL DBMS also allows you to export and import data, which is convenient when moving large amounts of information.
https://www.mysql.com/
HTML (English "hyper text markup language" - hypertext markup language) is a special markup language that is used to create sites on the Internet.
Browsers understand html perfectly and can interpret it in an understandable way. In general, any page on the site is html-code, which the browser translates into a user-friendly form. By the way, the code of any page is available to everyone.
https://www.w3.org/html/
Welcome to the Q&A site for web developers. Here you can ask a question about the problem you are facing and get answers from other experts. We have created a user-friendly interface so that you can quickly and free of charge ask a question about a web programming problem. We also invite other experts to join our community and help other members who ask questions. In addition, you can use our search for questions with a solution.
Ask about the real problem you are facing. Describe in detail what you are doing and what you want to achieve.
Our goal is to create a strong community in which everyone will support each other. If you find a question and know the answer to it, help others with your knowledge.