知識點
1.HTTP協議的簡介(見上節)
2.URLConnection同步請求
3.URLConnection異步請求
4.URLConnection異步請求Block版本
5.URLConnectionPOST請求
6.URLConnection的封裝
==================================
2.NSURL,用OC中用來表示URL的類
創建URL:
[NSURL URLWithString:urlStr];
=====================================
3.NSURLRequest,用來表示一個請求
//創建Request:
[NSURLRequest requestWithURL:url];
//創建帶超時的Request
[NSURLRequest requestWithURL:url cachePolicy:NSURLRequestUseProtocolCachePolicy timeoutInterval:0.01f];
//創建可變的Request,可修改Request的屬性,如Method等,POST用到
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];
request.HTTPMethod = @"POST";
//設置請求體
NSString *paramStr = @"username=qf1508&password=123456";
request.HTTPBody = [paramStr dataUsingEncoding:NSUTF8StringEncoding];
=====================================
4.NSURLConnection,表示一個請求響應的連接
//發送同步請求
[NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&error];
//發送異步請求
[NSURLConnection sendAsynchronousRequest:request queue:[NSOperationQueue mainQueue] completionHandler:^(NSURLResponse *response, NSData *data, NSError *connectionError) {}];
//發送異步請求,delegate版本
[NSURLConnection connectionWithRequest:request delegate:self];
=====================================
4.NSURLConnection的Delegate回調函數
//接收到服務器的響應
- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response;
//接收到服務器發送過來的數據,數據是分段發給我們的,所以這個方法會被調用多次
- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data;
//服務器所有的數據都發送完成之後,會調用這個方法
- (void)connectionDidFinishLoading:(NSURLConnection *)connection;
//請求失敗(url不合法、超時、網絡中斷等等)時會調用這個方法
- (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error;
=====================================
:ios9.0不支持http ,推薦https
1接口是https
2修改info.plist
<key>NSAppTransportSecurity</key>
<dict>
<key>NSAllowsArbitraryLoads</key>
<true/>
</dict>