我已尽力解决问题,但无法找到问题。这是代码
的iOS:
- (IBAction)login {
NSString *post = [NSString stringWithFormat: @"user=%@&pass=%@", _username, _password];
NSData *postData = [post dataUsingEncoding:NSASCIIStringEncoding allowLossyConversion:YES];
NSString *postLength = [NSString stringWithFormat:@"%lu", [postData length]];
NSMutableURLRequest *request = [[NSMutableURLRequest alloc] init] ;
[request setURL:[NSURL URLWithString:@"http://www.example.com/login.php"]];
[request setHTTPMethod:@"POST"];
[request setValue:postLength forHTTPHeaderField:@"Content-Length"];
[request setValue:@"application/x-www-form-urlencoded" forHTTPHeaderField:@"Content-Type"];
[request setTimeoutInterval:20.0];
[request setHTTPBody:postData];
[NSURLConnection connectionWithRequest:request delegate:self];
}
- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response {
_responseData = [[NSMutableData alloc] init];
}
- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data {
[_responseData appendData:data];
NSString *stringData = [[NSString alloc] initWithData:_responseData encoding:NSUTF8StringEncoding];
NSLog(@"%@", stringData);
}
- (NSCachedURLResponse *)connection:(NSURLConnection *)connection
return nil;
}
- (void)connectionDidFinishLoading:(NSURLConnection *)connection {
}
- (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error {
NSLog(@"%@", error);
}
PHP:
<?php
echo "Username: ".$_POST["user"]."<br>Password: ".$_POST["pass"];
?>
返回以下内容:
Username: <br>Password:
我一直试图弄清楚它有多长时间出错了。任何帮助将不胜感激。
答案 0 :(得分:0)
这对我来说很好用:
@interface Test : NSObject
-(void)userLogin;
@end
int main(int argc, const char * argv[]) {
@autoreleasepool {
Test *test = [[Test alloc] init];
[test userLogin];
}
return 0;
}
@implementation Test : NSObject
-(void)userLogin {
NSString *user = @"test";
NSString *pass = @"pass";
NSString *post = [NSString stringWithFormat: @"user=%@&pass=%@", user, pass];
NSData *postData = [post dataUsingEncoding:NSASCIIStringEncoding allowLossyConversion:YES];
NSString *postLength = [NSString stringWithFormat:@"%lu", [postData length]];
NSMutableURLRequest *request = [[NSMutableURLRequest alloc] init] ;
[request setURL:[NSURL URLWithString:@"www.example.com/login.php"]];
[request setHTTPMethod:@"POST"];
[request setValue:postLength forHTTPHeaderField:@"Content-Length"];
[request setValue:@"application/x-www-form-urlencoded" forHTTPHeaderField:@"Content-Type"];
[request setHTTPBody:postData];
NSURLConnection *conn = [[NSURLConnection alloc] initWithRequest:request delegate:self];
sleep(50);
NSLog(@"%@", conn);
}
@end
PHP:
<?php
file_put_contents('/tmp/test', print_r($_POST, true));
结果:
# cat /tmp/test
Array
(
[user] => test
[pass] => pass
)