NSURLRequest 與 NSMutableURLRequest 是 iOS 中常見的網路請求方式。GET 可直接把參數放在 URL;POST 則會把參數放進 HTTPBody。
NSString *urlStr = [NSString stringWithFormat:@"https://localhost/login.php?username=%@&password=%@", self.userName.text, self.userPwd.text];
NSURL *url = [NSURL URLWithString:urlStr];
NSURLRequest *request = [NSURLRequest requestWithURL:url];
[NSURLConnection sendAsynchronousRequest:request queue:[[NSOperationQueue alloc] init] completionHandler:^(NSURLResponse *response, NSData *data, NSError *connectionError) {
if (connectionError == nil) {
NSString *str = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
NSLog(@"%@", str);
}
}];NSURL *url = [NSURL URLWithString:@"https://localhost/login.php"];
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];
request.HTTPMethod = @"POST";
NSString *bodyStr = [NSString stringWithFormat:@"username=%@&password=%@", self.userName.text, self.userPwd.text];
request.HTTPBody = [bodyStr dataUsingEncoding:NSUTF8StringEncoding];
[NSURLConnection sendAsynchronousRequest:request queue:[[NSOperationQueue alloc] init] completionHandler:^(NSURLResponse *response, NSData *data, NSError *connectionError) {
if (connectionError == nil) {
NSString *str = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
NSLog(@"%@", str);
}
}];若要處理大型資料或分段接收,可實作 NSURLConnectionDataDelegate。
- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data {
[self.data appendData:data];
}
- (void)connectionDidFinishLoading:(NSURLConnection *)connection {
NSString *str = [[NSString alloc] initWithData:self.data encoding:NSUTF8StringEncoding];
NSLog(@"%@", str);
}更新 UI 時,應回到主執行緒執行,以避免線程安全問題。
[[NSOperationQueue mainQueue] addOperationWithBlock:^{
self.logonResult.text = str;
}];