1.NSURLConnection使用
- 1.1 NSURLConnection同步請求(GET)
(1)步驟
1. 設置請求路徑
2. 創建請求對象(默認是GET請求,且已經默認包含了請求頭)
3. 使用NSURLSession sendsync方法發送網絡請求
4. 接收到服務器的響應后,解析響應體
(2)相關代碼
//1.確定請求路徑
NSURL *url = [NSURL URLWithString:@"http://120.25.226.186:32812/login?username=singerYoung&pwd=singerYoung&type=XML"];
// NSURL *url = [NSURL URLWithString:@"http://120.25.226.186:32812/video?type=XML"];
//2.創建一個請求對象
NSURLRequest *request = [NSURLRequest requestWithURL:url];
//3.把請求發送給服務器
//sendSynchronousRequest 阻塞式的方法,會卡住線程
NSHTTPURLResponse *response = nil;
NSError *error = nil;
/*
第一個參數:請求對象
第二個參數:響應頭信息,當該方法執行完畢之后,該參數被賦值
第三個參數:錯誤信息,如果請求失敗,則error有值
*/
//該方法是阻塞式的,會卡住線程
NSData *data = [NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&error];
//4.解析服務器返回的數據
NSString *str = [[NSString alloc]initWithData:data encoding:NSUTF8StringEncoding];
- 1.2 NSURLConnection異步請求(GET-SendAsync)
(1)相關說明
01 該方法不會卡住當前線程,網絡請求任務是異步執行的
(2)相關代碼
//1.確定請求路徑
NSURL *url = [NSURL URLWithString:@"http://120.25.226.186:32812/login?username=singerYoung&pwd=singerYoung"];
//2.創建一個請求對象
NSURLRequest *request = [NSURLRequest requestWithURL:url];
//3.把請求發送給服務器,發送一個異步請求
/*
第一個參數:請求對象
第二個參數:回調方法在哪個線程中執行,如果是主隊列則block在主線程中執行,非主隊列則在子線程中執行
第三個參數:completionHandlerBlock塊:接受到響應的時候執行該block中的代碼
response:響應頭信息
data:響應體
connectionError:錯誤信息,如果請求失敗,那么該參數有值
*/
[NSURLConnection sendAsynchronousRequest:request queue:[[NSOperationQueue alloc]init] completionHandler:^(NSURLResponse * __nullable response, NSData * __nullable data, NSError * __nullable connectionError) {
//4.解析服務器返回的數據
NSString *str = [[NSString alloc]initWithData:data encoding:NSUTF8StringEncoding];
//轉換并打印響應頭信息
NSHTTPURLResponse *r = (NSHTTPURLResponse *)response;
NSLog(@"--%zd---%@--",r.statusCode,r.allHeaderFields);
}];
- 1.3 NSURLConnection異步請求(GET-代理)
(1)步驟
01 確定請求路徑
02 創建請求對象
03 創建NSURLConnection對象并設置代理
04 遵守NSURLConnectionDataDelegate協議,并實現相應的代理方法
05 在代理方法中監聽網絡請求的響應
(2)設置代理的幾種方法
//設置代理的第一種方式:自動發送網絡請求
NSURLConnection *conn = [[NSURLConnection alloc]initWithRequest:request delegate:self];
//設置代理的第二種方式:使用類方法設置代理,會自動發送網絡請求
NSURLConnection *conn = [NSURLConnection connectionWithRequest:request delegate:self];
/*
設置代理的第三種方式:
第一個參數:請求對象
第二個參數:誰成為NSURLConnetion對象的代理
第三個參數:是否馬上發送網絡請求,如果該值為YES則立刻發送,如果為NO則不會發送網路請求
*/
NSURLConnection *conn = [[NSURLConnection alloc]initWithRequest:request delegate:self startImmediately:NO];
//調用該方法控制網絡請求的發送(當為NO的時候,調用這方法會立即發送網絡請求)
[conn start];
//取消網絡請求
//[conn cancel];
(3)相關的代理方法
/*
1.當接收到服務器響應的時候調用
第一個參數connection:監聽的是哪個NSURLConnection對象
第二個參數response:接收到的服務器返回的響應頭信息
*/
- (void)connection:(nonnull NSURLConnection *)connection didReceiveResponse:(nonnull NSURLResponse *)response
/*
2.當接收到數據的時候調用,該方法會被調用多次
第一個參數connection:監聽的是哪個NSURLConnection對象
第二個參數data:本次接收到的服務端返回的二進制數據(可能是片段)
*/
- (void)connection:(nonnull NSURLConnection *)connection didReceiveData:(nonnull NSData *)data
/*
3.當服務端返回的數據接收完畢之后會調用
通常在該方法中解析服務器返回的數據
*/
-(void)connectionDidFinishLoading:(nonnull NSURLConnection *)connection
/*4.當請求錯誤的時候調用(比如請求超時)
第一個參數connection:NSURLConnection對象
第二個參數:網絡請求的錯誤信息,如果請求失敗,則error有值
*/
- (void)connection:(nonnull NSURLConnection *)connection didFailWithError:(nonnull NSError *)error
(4)其它知識點
01 關于消息彈窗第三方框架的使用
SVProgressHUD
02 字符串截取相關方法
- (NSRange)rangeOfString:(NSString *)searchString;
- (NSString *)substringWithRange:(NSRange)range;
- 1.4 NSURLConnection發送POST請求
(1)發送POST請求步驟
a.確定URL路徑
b.創建請求對象(可變對象)
c.修改請求對象的方法為POST,設置請求體(Data)
d.發送一個異步請求
e.補充:設置請求超時,處理錯誤信息,設置請求頭(如獲取客戶端的版本等等,請求頭是可設置可不設置的)
(2)相關代碼
//1.確定請求路徑
NSURL *url = [NSURL URLWithString:@"http://120.25.226.186:32812/login"];
//2.創建請求對象
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];
//2.1更改請求方法(POST必須大寫)
request.HTTPMethod = @"POST";
//2.2設置請求體
request.HTTPBody = [@"username=singerYoung&pwd=singerYoung" dataUsingEncoding:NSUTF8StringEncoding];
//2.3請求超時
request.timeoutInterval = 5;
//2.4設置請求頭(一般不自定義,因為請求體里包含了請求頭了,看公司和項目需要)
//獲取硬件設備版本號
//[UIDevice currentDevice].systemVersion
//注意,key是固定的
[request setValue:@"ios 9.0" forHTTPHeaderField:@"User-Agent"];
//3.發送請求(隊列決定block里的實在那個隊列里調用,并不是這整個方法)
[NSURLConnection sendAsynchronousRequest:request queue:[NSOperationQueue mainQueue] completionHandler:^(NSURLResponse * __nullable response, NSData * __nullable data, NSError * __nullable connectionError) {
//4.解析服務器返回的數據
if (connectionError) {
NSLog(@"--請求失敗-");
}else
{
NSLog(@"%@",[[NSString alloc]initWithData:data encoding:NSUTF8StringEncoding]);
}
}];
- 1.5 URL中文轉碼問題
get請求需要轉,post請求不需要轉
//1.確定請求路徑,如果字符串中有中文,那么需要對字符串進行中文轉碼
NSString *urlStr = @"http://120.25.226.186:32812/login2?username=小小羊&pwd=singerYoung";
NSLog(@"%@",urlStr);
//中文轉碼操作
urlStr = [urlStr stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
NSLog(@"%@",urlStr);
NSURL *url = [NSURL URLWithString:urlStr];
- Posted by *** singerYoung ***
- 聯系作者 簡書·singerYoung 新浪微博·小小羊run
- 原創文章,版權聲明:自由轉載-非商用-非衍生-保持署名