標籤:
iOS中遵循較為安全的HTTPS安全超文本協議,若想訪問遵循HTTP協議的網頁需要進行以下設定:
將代碼<key>NSAppTransportSecurity</key>
<dict>
<key>NSAllowsArbitraryLoads</key>
<true/>
</dict>
複製到
路徑下;
或者在info.plist檔案中添加以下欄位
請求方式分為GET和POST兩種方式;每種方式又包含同步和非同步兩種形式;同步會是應用程式出現卡頓現象,這裡只介紹非同步形式。
在iOS7之前使用NSURLConnection來進行網路的請求,iOS7之後前面的方法被重構,改為NSURLSession。先介紹NSURLConnection,雖然被重構但還是可以啟動並執行:
#pragma mark - NSURLConnection - 非同步get請求
- (IBAction)getAsynchronousRequest:(UIButton *)sender {
//1.建立url
NSURL *url = [NSURL URLWithString:GET_URL];//GET_URL是宏定義的網址,建立Header File,在其中宏定義網址。
宏定義:::::
#define GET_URL @"http://ipad-bjwb.bjd.com.cn/DigitalPublication/publish/Handler/APINewsList.ashx?date=20131129&startRecord=1&len=5&udid=1234567890&terminalType=Iphone&cid=213"
#define POST_URL @"http://ipad-bjwb.bjd.com.cn/DigitalPublication/publish/Handler/APINewsList.ashx"
#define POST_BODY @"date=20131129&startRecord=1&len=5&udid=1234567890&terminalType=Iphone&cid=213"
//2.建立請求
NSURLRequest *request = [NSURLRequest requestWithURL:url];
//3.串連伺服器
//方法一:Block方法實現,//參數1:請求對象 //參數2:線程隊列 //參數3:block
[NSURLConnection sendAsynchronousRequest:request queue:[NSOperationQueue mainQueue] completionHandler:^(NSURLResponse * _Nullable response, NSData * _Nullable data, NSError * _Nullable connectionError) {
if (connectionError == nil) {
//4.解析
NSDictionary *dic = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingAllowFragments error:nil];
NSLog(@"dic = %@", dic);
//先開闢子線程解析資料
//然後在主線程裡重新整理UI
}
}];
//方法二:使用delegate實現<NSURLConnectionDataDelegate>,將上面的3.4.兩步替換為,同時使用先關代理方法
//[NSURLConnection connectionWithRequest:request delegate:self];
}
#pragma mark - NSURLConnectionDataDelegate相關的代理方法
//伺服器開始響應
- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response {
self.resultData = [NSMutableData new];//初始化資料
}
//開始接收資料這個方法會重複執行,得到的每段資料拼接在一起就可以了
- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data {
[self.resultData appendData:data];
}
//結束伺服器
- (void)connectionDidFinishLoading:(NSURLConnection *)connection {
//進行資料解析(根據url連結到的具體內容進行解析)
NSDictionary *dic = [NSJSONSerialization JSONObjectWithData:self.resultData options:NSJSONReadingAllowFragments error:nil];
NSLog(@"dic = %@", dic);
}
#pragma mark -NSURLConnection - 非同步post請求
- (IBAction)postAsynchronousRequest:(UIButton *)sender {
//1.建立url
NSURL *url = [NSURL URLWithString:POST_URL];
//2.建立請求
NSMutableURLRequest *mutableRequest = [NSMutableURLRequest requestWithURL:url];
//2.5設定body
//建立一個連結字串
NSString *dataString = POST_BODY;
//對連接字串進行編碼
NSData *postData = [dataString dataUsingEncoding:NSUTF8StringEncoding];
//佈建要求格式
[mutableRequest setHTTPMethod:@"POST"];
//佈建要求體
[mutableRequest setHTTPBody:postData];
//3.連結的伺服器
[NSURLConnection sendAsynchronousRequest:mutableRequest queue:[NSOperationQueue mainQueue] completionHandler:^(NSURLResponse * _Nullable response, NSData * _Nullable data, NSError * _Nullable connectionError) {
if (connectionError == nil) {
NSDictionary *dic = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingAllowFragments error:nil];
}
}];
}
#pragma mark - NSURLSession - get請求block實現
- (IBAction)getRequest:(UIButton *)sender {
//方式一:使用block
//1.建立url
NSURL *url = [NSURL URLWithString:GET_URL];
//2.建立請求NSURLRequest
NSURLRequest *request = [NSURLRequest requestWithURL:url];
//2.建立session對象
NSURLSession *session = [NSURLSession sharedSession];
//3.建立task請求任務
NSURLSessionDataTask *task = [session dataTaskWithRequest:request completionHandler:^(NSData * _Nullable data, NSURLResponse * _Nullable response, NSError * _Nullable error) {
//4.解析相關的資料//這裡block執行步驟比較靠後,不是在//2.建立session對象之後馬上執行
if (error == nil) {
NSDictionary *dic = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingAllowFragments error:nil];
}
}];
//5.核心步:啟動任務【千萬不要忘記】============
//原因:NSURLSessionTask執行個體出來的任務處於掛起狀態,如果不啟動,不會走block中的實現部分
[task resume];
#pragma mark - NSURLSession - get請求協議實現
NSURL *url = [NSURL URLWithString:GET_URL];
//2.建立session
//參數1:模式的設定
/*
* defaultSessionConfiguration 預設會話模式
* ephemeralSessionConfiguration 瞬時會話模式
* backgroundSessionConfigurationWithIdentifier 後台會話模式
*/
//參數2:代理
//參數3:主線程隊列
NSURLSession *session = [NSURLSession sessionWithConfiguration:[NSURLSessionConfiguration defaultSessionConfiguration] delegate:self delegateQueue:[NSOperationQueue mainQueue]];//遵循協議<NSURLSessionDataDelegate>
//3.建立task
NSURLSessionDataTask *task = [session dataTaskWithURL:url];
//4.啟動
[task resume];
#pragma mark - NSURLSessionDataDelegate協議的實現方法
//伺服器開始響應
- (void)URLSession:(NSURLSession *)session dataTask:(NSURLSessionDataTask *)dataTask didReceiveResponse:(NSURLResponse *)response completionHandler:(void (^)(NSURLSessionResponseDisposition))completionHandler {
//允許伺服器響應[在這個地方只有允許伺服器響應了才會接收到資料]
completionHandler(NSURLSessionResponseAllow);
//初始化data稍後進行片段的拼接儲存
self.resultData = [NSMutableData data];
}
//接收資料拼接
- (void)URLSession:(NSURLSession *)session dataTask:(NSURLSessionDataTask *)dataTask didReceiveData:(NSData *)data {
//反覆執行,然後拼接相關的片段
[self.resultData appendData:data];
}
//資料接收完成,網路請求結束
- (void)URLSession:(NSURLSession *)session task:(NSURLSessionTask *)task didCompleteWithError:(NSError *)error {
//解析
if (error == nil) {
NSDictionary *dic = [NSJSONSerialization JSONObjectWithData:self.resultData options:NSJSONReadingAllowFragments error:nil];
NSLog(@"dic = %@", dic);
}
}
#pragma mark - NSURLSession - post請求
- (IBAction)postRequest:(UIButton *)sender {
//1.建立url
NSURL *url = [NSURL URLWithString:POST_URL];
//2.建立請求
NSMutableURLRequest *mutableRequest = [NSMutableURLRequest requestWithURL:url];
//2.5核心設定body
NSString *bodyString = POST_BODY;
NSData *postData = [bodyString dataUsingEncoding:NSUTF8StringEncoding];
[mutableRequest setHTTPMethod:@"POST"];
[mutableRequest setHTTPBody:postData];
//3.建立session對象
NSURLSession *session = [NSURLSession sharedSession];
//4.建立task對象
NSURLSessionDataTask *task = [session dataTaskWithRequest:mutableRequest completionHandler:^(NSData * _Nullable data, NSURLResponse * _Nullable response, NSError * _Nullable error) {
//5.解析
if (error == nil) {
NSDictionary *dic = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingAllowFragments error:nil];
NSLog(@"dic = %@", dic);
}
}];
//6.啟動任務
[task resume];
}
iOS之網路請求