iOS網路資料請求
阿新 • • 發佈:2019-01-24
HTTP和HTTPS協議
- URL全稱是Uniform ResourceLocator(統一字典定位符)通過一個URL,能夠找到網際網路上唯一的11個資源
- URL就是資源的地址,位置,網際網路上的每個資源都有一個唯一URL
- 協議:不同的協議代表著不同國的資源查詢方式,資源傳輸方式
- 主機地址:存放資源的主機的IP地址(域名)
- 路徑:資源在主機中的位置
- HTTP協議:Hyper Text Transfer Protocol(超文字傳輸協議)是用於從全球資訊網(www)伺服器傳送超文字到本地瀏覽器的傳輸協議,HTTP是一個應用層協議,由請求和響應構成,是一個標準的客戶端伺服器模型,客戶端向伺服器傳送一個請求報文,伺服器以一個狀態作為響應.
- C/S模式:Client和Server常常分別處在相距很遠的兩臺計算機上,Client程式任務是將使用者的要求提交給Server程式,再將server程式返回的結果以特定的形式顯示給使用者;Server程式的任務是接收客戶程式提出的服務請求,進行相應的處理,再將結果返回給客戶程式.
- HTTPS(Secure Hyper Text Transfer Protocol)安全超文字傳輸協議,它是一個安全通道.基於HTTP開發,用於在客戶計算機和伺服器之間的交換資訊,它使用安全套接字層(SSL)進行資訊交換,簡單來說它是HTTP的安全版.HTTPS協議使用SSL在傳送和接受方通過交換共和的密匙來實現,因此,所傳送的資料不容易被網路黑客截獲和解密.
- SSL是Netscape公司所提出安全保密協議,執行在TCP/IP層之上,應用層之下,為應用層提供加密資料通道
HTTP和HTTPS的異同:
- https協議需要到cd申請證書,一般免費證書很少,需要交費.
- http是超文字傳輸協議,資訊是明文傳輸,https則是具有安全性的ssl加密傳輸協議
- http和https使用的是完全不同的連結方式,用的埠也不一樣,前者是80,後者是443
- http的連結很簡單,是無狀態的
- https是協議是由SSL+HTTP協議構建的可進行加密傳輸,身份認證的網路協議,要比http安全.
HTTP協議的常見的請求方式:GET和POST
- 相同點:都能給伺服器傳輸資料.
不同點:
給伺服器傳輸資料的方式不同:
- GET:通過網址字串.
- POST:通過data.
傳輸資料的大小:
- GET:網址字串最多255.
- 使用NSData,容量超過1G.
安全性:
- GET:所有傳輸給服務的資料,顯示的網址裡,類似於密碼的明文輸入,直接可見.
- POST:資料被轉成NSData(二進位制資料),類似於密碼的密文輸入,無法直接讀取.
HTTP協議請求如何實現
同步請求
GetSynchronization get同步請求
- (void)getAndSynchronization {
//1 建立網址物件
NSString *urlString = @"http://ipad-bjwb.bjd.com.cn/DigitalPublication/publish/Handler/APINewsList.ashx?date=20151031&startRecord=1&len=5&udid=1234567890&terminalType=Iphone&cid=213";
NSURL *url = [NSURL URLWithString:urlString];
//2 建立請求物件
NSURLRequest *request = [NSURLRequest requestWithURL:url];
//3 傳送請求,連線伺服器(這個方法雖然能過時了但是能使用)
NSData *data = [NSURLConnection sendSynchronousRequest:request returningResponse:nil error:nil];
//4 解析
if (data) {
self.getDic = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingAllowFragments error:nil];
// NSLog(@"%@",self.getDic);
if(self.getDic){
//判斷物件是否支援json格式
if ([NSJSONSerialization isValidJSONObject:self.getDic]) {
//將字典轉換為json串
NSData *strData = [NSJSONSerialization dataWithJSONObject:self.getDic options:NSJSONWritingPrettyPrinted error:nil];
if (strData) {
//將data轉換為字串
NSString *str = [[NSString alloc] initWithData:strData encoding:NSUTF8StringEncoding];
NSLog(@"%@",str);
}
}
}
} else {
NSLog(@"請求失敗");
}
}
post同步請求
- (void)postAndSynchronization {
//第一步:建立URL
NSURL *url = [NSURL URLWithString:@"http://ipad-bjwb.bjd.com.cn/DigitalPublication/publish/Handler/APINewsList.ashx"];
//第二步:建立請求
NSString *postStr = @"date=20151031&startRecord=1&len=5&udid=1234567890&terminalType=Iphone&cid=213";
NSData *postData = [postStr dataUsingEncoding:NSUTF8StringEncoding];
NSMutableURLRequest *request = [[NSMutableURLRequest alloc] initWithURL:url cachePolicy:NSURLRequestUseProtocolCachePolicy timeoutInterval:10];
//設定請求方式為POST,預設為GET
request.HTTPMethod = @"POST";
//設定body
request.HTTPBody = postData;
//第三方:連線伺服器
NSData *received = [NSURLConnection sendSynchronousRequest:request returningResponse:nil error:nil];
NSMutableDictionary *dic = [NSMutableDictionary dictionary];
dic = [NSJSONSerialization JSONObjectWithData:received options:NSJSONReadingAllowFragments error:nil];
NSLog(@"%@",dic);
}
非同步請求
非同步block請求
- (void)getAndAsychronousBlock {
//網址
NSURL *url = [NSURL URLWithString:@"http://mapi.weibo.com/2/remind/unread_count?remind_version=199&networktype=wifi&with_comment_attitude=1&ext_all=0&moduleID=700&c=android&i=ed0d41d&s=f32076c0&ua=Xiaomi-MI%203__weibo__6.4.0__android__android4.4.4&wm=20005_0002&aid=01AtCI_i9CnkwZ8amfinkM-ZJWFOpF0gsEw_rwX43XUPpDgT8.&idc=&v_f=2&from=1064095010&gsid=_2A256CymIDeTxGeNG6FQQ9i_NwjqIHXVWgTpArDV6PUJbrdAKLXjFkWoNYAQ8b7QA8jEG-5JLCblfTetI5w..&lang=zh_CN&skin=default&oldwm=9975_0028&sflag=1&with_settings=1&unread_message=1&with_page_group=1"];
//請求
NSURLRequest *request = [NSURLRequest requestWithURL:url];
//非同步連線block方式
[NSURLConnection sendAsynchronousRequest:request queue:[NSOperationQueue mainQueue] completionHandler:^(NSURLResponse * _Nullable response, NSData * _Nullable data, NSError * _Nullable connectionError) {
NSMutableDictionary *dic = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingAllowFragments error:nil];
NSLog(@"%@",dic);
NSLog(@"請求到資料了");
}];
NSLog(@"我在block的地下");
}
post 非同步協議代理方式
- (void)postAndDelegate {
//網址
/*
date=20151031&startRecord=1&len=5&udid=1234567890&terminalType=Iphone&cid=213
*/
NSURL *url = [NSURL URLWithString:@"http://ipad-bjwb.bjd.com.cn/DigitalPublication/publish/Handler/APINewsList.ashx"];
//post請求物件構建
NSMutableURLRequest *mutableURLRequest = [NSMutableURLRequest requestWithURL:url];
//設定請求方式
[mutableURLRequest setHTTPMethod:@"POST"];
//設定引數
//需要將引數轉換為data型別
NSString *str = @"date=20151031&startRecord=1&len=5&udid=1234567890&terminalType=Iphone&cid=213";
NSData *data = [str dataUsingEncoding:NSUTF8StringEncoding];
[mutableURLRequest setHTTPBody:data];
//請求超時
[mutableURLRequest setTimeoutInterval:60];
//需要設定代理,所以我們需要一個連線物件
NSURLConnection *connection = [NSURLConnection connectionWithRequest:mutableURLRequest delegate:self];
}
#pragma mark - NSURLConnectionDelegate,NSURLConnectionDataDelegate協議方法
//伺服器開始響應,準備返回資料
- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response {
//初始化receiveData,用來接收資料
self.receiveData = [[NSMutableData alloc] init];
NSLog(@"開始返回響應");
}
//客戶端接收資料
- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data {
//返回的資料不是一次返回而是分批返回,所以我們需要一個可變的data型別來接收它
NSLog(@"開始接收資料");
[self.receiveData appendData:data];
}
//資料請求完畢
- (void)connectionDidFinishLoading:(NSURLConnection *)connection {
NSLog(@"資料已經返回完畢");
NSMutableDictionary *dict = [NSJSONSerialization JSONObjectWithData:self.receiveData options:NSJSONReadingAllowFragments error:nil];
if (dict) {
if ([NSJSONSerialization isValidJSONObject:dict]) {
NSData *data = [NSJSONSerialization dataWithJSONObject:dict options:NSJSONWritingPrettyPrinted error:nil];
NSString *str = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
NSLog(@"%@",str);
}
}
}
//網路請求失敗
- (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error {
NSLog(@"請求出錯----%@",error);
}
iOS7之後請求變化
NSURLSession get請求(block)
- (void)sessionAndGet {
//網址
NSURL *url = [NSURL URLWithString:@"http://ipad-bjwb.bjd.com.cn/DigitalPublication/publish/Handler/APINewsList.ashx?date=20151031&startRecord=1&len=5&udid=1234567890&terminalType=Iphone&cid=213"];
//建立載入資料任務
NSURLSessionDataTask *dataTask = [[NSURLSession sharedSession] dataTaskWithURL:url completionHandler:^(NSData * _Nullable data, NSURLResponse * _Nullable response, NSError * _Nullable error) {
NSMutableDictionary *dic = [NSMutableDictionary dictionary];
dic = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingAllowFragments error:nil];
NSLog(@"%@",dic);
}];
//啟動任務
[dataTask resume];
}
NSURLSession post請求block
- (void)sessionAndPost {
//網址
NSURL *url = [NSURL URLWithString:@"http://ipad-bjwb.bjd.com.cn/DigitalPublication/publish/Handler/APINewsList.ashx"];
//設定NSMutableURLRequest
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];
//設定請求方式
request.HTTPMethod = @"POST";
//設定引數
request.HTTPBody = [@"date=20151031&startRecord=1&len=5&udid=1234567890&terminalType=Iphone&cid=213 " dataUsingEncoding:NSUTF8StringEncoding];
//建立一個session物件,用來進行post請求
NSURLSession *session = [NSURLSession sharedSession];
//建立任務
NSURLSessionTask *task = [session dataTaskWithRequest:request completionHandler:^(NSData * _Nullable data, NSURLResponse * _Nullable response, NSError * _Nullable error) {
//解析
NSMutableDictionary *mDict = [NSMutableDictionary dictionary];
mDict = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingAllowFragments error:nil];
NSLog(@"%@",mDict);
}];
//啟動任務
[task resume];
}
#pragma mark - NSURLSessionDataDelegate,,NSURLSessionDelegate協議方法
//NSURLSessionDataDelegate代理方法
//NSURLSession提供了block方式處理返回資料的簡單方式,但如果想要在接收資料過程中做進一步的處理,仍然可以呼叫相關的協議方法,NSURLSession的代理方法和NSURLConnection有些類似,都是分為接收響應,接收資料,請求完成幾個階段
//使用代理方法我們需要設定代理,但是session的delegate屬性是隻讀的,要想設定代理只能通過這種方式建立session
- (void)sessionAndDelegate {
//網址
NSURL *url = [NSURL URLWithString:@"http://ipad-bjwb.bjd.com.cn/DigitalPublication/publish/Handler/APINewsList.ashx"];
//建立一個session物件,用來進行請求
NSURLSession *session = [NSURLSession sessionWithConfiguration:[NSURLSessionConfiguration defaultSessionConfiguration] delegate:self delegateQueue:[NSOperationQueue mainQueue]];
//建立任務(因為要使用代理方法,就不需要block方式初始化)
// NSURLSessionDataTask *task = [session dataTaskWithURL:url];//這個方法只能用在get請求中
NSURLSessionDataTask *task = [session dataTaskWithRequest:[NSURLRequest requestWithURL:url]];
//啟動任務
[task resume];
}
//代理方法
//接收伺服器響應
- (void)URLSession:(NSURLSession *)session dataTask:(NSURLSessionDataTask *)dataTask didReceiveResponse:(NSURLResponse *)response completionHandler:(void (^)(NSURLSessionResponseDisposition))completionHandler {
//允許處理伺服器的響應,才會繼續接收伺服器返回的資料
completionHandler(NSURLSessionResponseAllow);
//當網路請求基於http協議時(url以http開頭),response本質為NSHTTPURLResponse型別
NSHTTPURLResponse *httpResponse = (NSHTTPURLResponse*)response;
//建立空的可變的data,準備接收伺服器傳回的data片段
self.recervedData = [NSMutableData dataWithCapacity:40];
}
//接收伺服器資料(可能多次,手動拼接資料)
- (void)URLSession:(NSURLSession *)session dataTask:(NSURLSessionDataTask *)dataTask didReceiveData:(NSData *)data {
//處理每次收到的資料
//將每次接收到的data片段,拼接到receivedData中
[self.recervedData appendData:data];
}
//請求結果(失敗後error物件被賦值錯誤資訊)
- (void)URLSession:(NSURLSession *)session task:(NSURLSessionTask *)task didCompleteWithError:(NSError *)error {
//請求完成,成功或者失敗的處理
NSMutableDictionary *dic = [[NSMutableDictionary alloc] init];
dic = [NSJSONSerialization JSONObjectWithData:self.recervedData options:NSJSONReadingAllowFragments error:nil];
NSLog(@"%@",dic);
}
下載
- (void)downLoadTask {
//建立網址
NSURL *url = [NSURL URLWithString:@"http://mapi.weibo.com/2/remind/unread_count?remind_version=199&networktype=wifi&with_comment_attitude=1&ext_all=0&moduleID=700&c=android&i=ed0d41d&s=f32076c0&ua=Xiaomi-MI%203__weibo__6.4.0__android__android4.4.4&wm=20005_0002&aid=01AtCI_i9CnkwZ8amfinkM-ZJWFOpF0gsEw_rwX43XUPpDgT8.&idc=&v_f=2&from=1064095010&gsid=_2A256CymIDeTxGeNG6FQQ9i_NwjqIHXVWgTpArDV6PUJbrdAKLXjFkWoNYAQ8b7QA8jEG-5JLCblfTetI5w..&lang=zh_CN&skin=default&oldwm=9975_0028&sflag=1&with_settings=1&unread_message=1&with_page_group=1"];
//建立session物件
NSURLSession *session = [NSURLSession sharedSession];
//建立下載的任務模式(會話模式)
NSURLSessionDownloadTask *downLoadTask = [session downloadTaskWithURL:url completionHandler:^(NSURL * _Nullable location, NSURLResponse * _Nullable response, NSError * _Nullable error) {
if (error) {
NSLog(@"error:%@",error.description);
} else {
//下載好的檔案儲存的路徑是在一個臨時檔案中/Users/xalo/Desktop/
//建立一個需要儲存下載檔案的路徑
NSURL *targetURL = [NSURL fileURLWithPath:@"/Users/xalo/Desktop/herJSON.json"];
//將臨時路徑下的檔案拷貝到桌面檔案
NSFileManager *manager = [NSFileManager defaultManager];
//copy
[manager copyItemAtURL:location toURL:targetURL error:nil];
//move
// [manager moveItemAtURL:location toURL:targetURL error:nil];
NSLog(@"location:%@",location);
}
}];
//啟動任務
[downLoadTask resume];
}