iOS之NSURLRequest NSMutableURLRequest 數據請求
get 請求
[objc] view plaincopy
#pragma mark - GET登錄
- (void)getLogon
{
// 1. URL
NSString *urlStr = [NSString stringWithFormat:@"http://localhost/login.php?username=%@&password=%@", self.userName.text, self.userPwd.text];
NSURL *url = [NSURL URLWithString:urlStr];
// 2. Request
NSURLRequest *request = [NSURLRequest requestWithURL:url];
// 3. Connection
// 1> 登錄完成之前,不能做後續工作!
// 2> 登錄進行中,可以允許用戶乾點別的會更好!
// 3> 讓登錄操作在其他線程中進行,就不會阻塞主線程的工作
// 4> 結論:登陸也是異步訪問,中間需要阻塞住
[NSURLConnection sendAsynchronousRequest:request queue:[[NSOperationQueue alloc] init] completionHandler:^(NSURLResponse *response, NSData *data, NSError *connectionError) {
if (connectionError == nil) {
// 網絡請求結束之後執行!
// 將Data轉換成字符串
NSString *str = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
// num = 2
NSLog(@"%@ %@", str, [NSThread currentThread]);
// 更新界面
[[NSOperationQueue mainQueue] addOperationWithBlock:^{
self.logonResult.text = @"登錄完成";
}];
}
}];
// num = 1
NSLog(@"come here %@", [NSThread currentThread]);
NSURLResponse *response = nil;
// 1. &response真的理解了嗎?
// 2. error:爲什麼是NULL,而不是nil
// NULL是C語言的 = 0
// 在C語言中,如果將指針的地址指向0就不會有危險
// nil是OC的,是一個空對象發送消息不會出問題
// [response MIMEType];
[NSURLConnection sendSynchronousRequest:request returningResponse:&response error:NULL];
}
post請求
[objc] view plaincopy
#pragma mark - POST登錄
- (void)postLogon
{
// 1. URL
NSURL *url = [NSURL URLWithString:@"http://localhost/login.php"];
// 2. 請求(可以改的請求)
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];
// ? POST
// 默認就是GET請求
request.HTTPMethod = @"POST";
// ? 數據體
NSString *str = [NSString stringWithFormat:@"username=%@&password=%@", self.userName.text, self.userPwd.text];
// 將字符串轉換成數據
request.HTTPBody = [str dataUsingEncoding:NSUTF8StringEncoding];
// 3. 連接,異步
[NSURLConnection sendAsynchronousRequest:request queue:[[NSOperationQueue alloc] init] completionHandler:^(NSURLResponse *response, NSData *data, NSError *connectionError) {
if (connectionError == nil) {
// 網絡請求結束之後執行!
// 將Data轉換成字符串
NSString *str = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
// num = 2
NSLog(@"%@ %@", str, [NSThread currentThread]);
// 更新界面
[[NSOperationQueue mainQueue] addOperationWithBlock:^{
self.logonResult.text = str;
}];
}
}];
// num = 1
NSLog(@"come here %@", [NSThread currentThread]);
}
使用NSURLConnection有兩種方式: 第一種 如上, 第二種實現 NSURLConnectionDataDelegate 代理
[objc] view plaincopy
- (void)getLogon
{
// 1. URL
NSString *urlStr = [NSString stringWithFormat:@"http://localhost/login.php?username=%@&password=%@", self.userName.text, self.myPwd];
NSLog(@"%@", self.myPwd);
NSURL *url = [NSURL URLWithString:urlStr];
// 2. Request
NSURLRequest *request = [NSURLRequest requestWithURL:url];
// 3. 連接,已經10多歲了
// 是一個很古老的技術
NSURLConnection *connection = [NSURLConnection connectionWithRequest:request delegate:self];
// 開始工作,在很多多線程技術中,start run
dispatch_async(dispatch_queue_create("demo", DISPATCH_QUEUE_CONCURRENT), ^{
[connection start];
});
}
#pragma mark - NSURLConnectionDataDelegate代理方法
#pragma mark 接受到響應
- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response
{
// 準備工作
// 按鈕點擊就會有網絡請求,爲了避免重複開闢空間
if (!self.data) {
self.data = [NSMutableData data];
} else {
[self.data setData:nil];
}
}
#pragma mark 接收到數據,如果數據量大,例如視頻,會被多次調用
- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data
{
// 拼接數據,二進制流的體現位置
[self.data appendData:data];
}
#pragma mark 接收完成,做最終的處理工作
- (void)connectionDidFinishLoading:(NSURLConnection *)connection
{
// 最終處理
NSString *str = [[NSString alloc] initWithData:self.data encoding:NSUTF8StringEncoding];
NSLog(@"%@ %@", str, [NSThread currentThread]);
}
#pragma mark 出錯處理,網絡的出錯可能性非常高
- (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error
{
NSLog(@"%@", error.localizedDescription);
}
注: 更新UI都要在主線程更新,原因要保證線程安全
[objc] view plaincopy
// 更新界面
[[NSOperationQueue mainQueue] addOperationWithBlock:^{
self.logonResult.text = str;
}];