網(wǎng)絡(luò)請(qǐng)求

網(wǎng)絡(luò)請(qǐng)求

http和https

URL

  • URL的基本格式 = 協(xié)議://主機(jī)地址/路徑
  • 協(xié)議:不同的協(xié)議代表不同的資源查找方式和資源的傳輸方式
  • 主機(jī)地址:存放資源的主機(jī)的IP地址(域名)
  • 路徑:資源在主機(jī)中的位置

C/S模式

  • client和server在相距很遠(yuǎn)的計(jì)算機(jī)上
  • client是將用戶的要求提交給server,再將server返回的結(jié)果展示給用戶
  • server是將接受用戶程序提出的服務(wù)請(qǐng)求,進(jìn)行相應(yīng)的處理,再講結(jié)果返還給用戶

HTTPS

  • 安全超文本傳輸協(xié)議,在HTTP基礎(chǔ)上使用SSL進(jìn)行信息交換
  • SSL:是運(yùn)行在TCP和IP層之上,應(yīng)用層之下的,為應(yīng)用程序提供加密數(shù)據(jù)通道
  • https協(xié)議需要到CA申請(qǐng)證書(shū),一般需要收費(fèi)
  • http和https使用完全不同的連接方式,所以端口也不一樣,前者80,后者443
  • http的鏈接簡(jiǎn)單,是無(wú)狀態(tài)的,傳輸完一次數(shù)據(jù)就立刻斷開(kāi)

get和post

  • get是通過(guò)網(wǎng)址字符串傳輸數(shù)據(jù),post是通過(guò)data
  • get允許網(wǎng)址字符串最多255字節(jié),post使用NSdata,容量超過(guò)1G(實(shí)際允許不超過(guò)4G)
  • get的所有傳輸給服務(wù)的數(shù)據(jù),都會(huì)顯示在網(wǎng)址里,直接可見(jiàn)的,而post的數(shù)據(jù)被轉(zhuǎn)成NSData,無(wú)法直接讀取,所以較為安全

實(shí)現(xiàn)網(wǎng)絡(luò)編程

  • 若網(wǎng)址字符串URLString中有漢字,需要用一下方式轉(zhuǎn)碼
str  = [str stringByAddingPercentEscapesUsingEncoding:[ NSCharacterSet URLQueryAllowedCharacterSet]];

NSURLConnection(ios9之后已經(jīng)棄用了)

get請(qǐng)求

  • 發(fā)送同步的get請(qǐng)求并解析數(shù)據(jù)
//定義的宏,一種是get用到的url,一種是post用到的url
#define KURL @"http://ipad-bjwb.bjd.com.cn/DigitalPublication/publish/Handler/APINewsList.ashx?date=20151101&startRecord=1&len=5&udid=1234567890&terminalType=Iphone&cid=213"
#define PURL @"http://ipad-bjwb.bjd.com.cn/DigitalPublication/publish/Handler/APINewsList.ashx"
    //發(fā)送同步的get請(qǐng)求
    NSURL *url  =[NSURL URLWithString:KURL];
    //    NSLog(@"%@,%@",url.scheme,url.host);
    //    1.url 2.httpcache的方式 3.超時(shí)時(shí)間
    NSURLRequest *request = [NSURLRequest requestWithURL:url cachePolicy:NSURLRequestUseProtocolCachePolicy timeoutInterval:10];
    //    發(fā)送請(qǐng)求
    NSURLResponse *response = nil;
    NSData *data = [NSURLConnection sendSynchronousRequest:request returningResponse:&response error:nil];
    if (data) {
        id json = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingAllowFragments error:nil];
        NSLog(@"%@",json);
        //response是響應(yīng)(包含響應(yīng)頭和響應(yīng)體)
        NSLog(@"%@",response);
    }
  • 發(fā)送異步的get請(qǐng)求(block方式)并解析數(shù)據(jù)
//異步get
    NSURL *url = [NSURL URLWithString:KURL];
    NSURLRequest *request = [NSURLRequest requestWithURL:url];
    //    1.request 2. 主隊(duì)列 3. 返回結(jié)果的block
    [NSURLConnection sendAsynchronousRequest:request queue:[NSOperationQueue mainQueue] completionHandler:^(NSURLResponse * _Nullable response, NSData * _Nullable data, NSError * _Nullable connectionError) {
        id json = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingAllowFragments error:nil];
        NSLog(@"%@",json);
    }];
    NSLog(@"先走這里");
  • 發(fā)送異步的get請(qǐng)求(代理方式)并解析數(shù)據(jù)
   //代理異步get(事先引入代理NSURLConnectionDataDelegate)
- (void)delegateGet
{
    NSURL *url = [NSURL URLWithString:KURL];
    //    創(chuàng)建請(qǐng)求
    NSURLRequest *request = [NSURLRequest requestWithURL:url];
    //    連接
    NSURLConnection *connection = [NSURLConnection connectionWithRequest:request delegate:self];
    //    開(kāi)始請(qǐng)求
    [connection start];
    //
    //    [connection cancel]; //取消
}
    //服務(wù)器接收到請(qǐng)求,開(kāi)始響應(yīng),準(zhǔn)備返回?cái)?shù)據(jù)
- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response
{

}
//接收數(shù)據(jù)(如果data比較大,會(huì)走很多次,需要拼接)
- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data
{
    //    把請(qǐng)求到的數(shù)據(jù)data拼接
    [self.data appendData:data];
}
//請(qǐng)求數(shù)據(jù)結(jié)束
- (void)connectionDidFinishLoading:(NSURLConnection *)connection
{
    id json = [NSJSONSerialization JSONObjectWithData:self.data options:NSJSONReadingAllowFragments error:nil];
    NSLog(@"%@",json);
}
//失敗
- (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error
{

}

post

  • 發(fā)送異步的post請(qǐng)求(block)并解析數(shù)據(jù)
#pragma mark 異步post
//異步post
- (void)post
{
    //POST
    NSURL *url = [NSURL URLWithString:PURL];
    NSMutableURLRequest *requset = [NSMutableURLRequest requestWithURL:url];
    //    設(shè)置請(qǐng)求方式(post請(qǐng)求方式和參數(shù)必須設(shè)置)
    requset.HTTPMethod =@"POST";
    //    設(shè)置請(qǐng)求參數(shù)
    NSString *str =@"date=20151101&startRecord=1&len=5&udid=1234567890&terminalType=Iphone&cid=213";
    NSData *data = [str dataUsingEncoding:NSUTF8StringEncoding];
    requset.HTTPBody = data;
    //    設(shè)置請(qǐng)求頭
    //    requset setValue:<#(nullable NSString *)#> forHTTPHeaderField:<#(nonnull NSString *)#>
    [NSURLConnection sendAsynchronousRequest:requset queue:[NSOperationQueue mainQueue] completionHandler:^(NSURLResponse * _Nullable response, NSData * _Nullable data, NSError * _Nullable connectionError) {
        id json = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingAllowFragments error:nil];
        NSLog(@"%@",json);
    }];
}
  • 發(fā)送異步的post請(qǐng)求(代理)并解析數(shù)據(jù)
//代理異步post(代理方法與get是一樣的,并且實(shí)現(xiàn)原理是相同的)
- (void)delegatePost
{
    NSURL *url = [NSURL URLWithString:PURL];
    NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];
    request.HTTPMethod = @"POST";
    NSString *str = @"date=20151101&startRecord=1&len=5&udid=1234567890&terminalType=Iphone&cid=213";
    NSData *data = [str dataUsingEncoding:NSUTF8StringEncoding];
    request.HTTPBody = data;
    NSURLConnection *connection = [NSURLConnection connectionWithRequest:request delegate:self];
    [connection start];
}

NSURLSession

get

  • 發(fā)送異步的get請(qǐng)求(block)并解析數(shù)據(jù)
- (void)blockGet
{
    //sessionGet
    //初始化session
    NSURLSession *session = [NSURLSession sharedSession];
    //    get請(qǐng)求
    NSURLSessionDataTask *task =[session dataTaskWithURL:[NSURL URLWithString:@"http://ipad-bjwb.bjd.com.cn/DigitalPublication/publish/Handler/APINewsList.ashx?date=20151101&startRecord=1&len=5&udid=1234567890&terminalType=Iphone&cid=213"] completionHandler:^(NSData * _Nullable data, NSURLResponse * _Nullable response, NSError * _Nullable error) {
        id json = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingAllowFragments error:nil];
        NSLog(@"%@",json);
    }];
    //開(kāi)啟任務(wù)(默認(rèn)掛起,需要手動(dòng)開(kāi)啟)
    [task resume];
}
  • 發(fā)送異步的get請(qǐng)求(代理)并解析數(shù)據(jù)
- (void)delegateGet
{
    //    控制任務(wù)的相關(guān)屬性(事先引入代理NSURLSessionDataDelegate)
    NSURLSessionConfiguration *configuration =  [NSURLSessionConfiguration defaultSessionConfiguration];
    //初始化session
    //1.任務(wù)的控制面板 2.代理 3.代理回調(diào)的線程(一般是主線程)
    NSURLSession *session  = [NSURLSession sessionWithConfiguration:configuration delegate:self delegateQueue:[NSOperationQueue mainQueue]];
    NSURLSessionDataTask *dataTask = [session dataTaskWithURL:[NSURL URLWithString:@"http://ipad-bjwb.bjd.com.cn/DigitalPublication/publish/Handler/APINewsList.ashx?date=20151101&startRecord=1&len=5&udid=1234567890&terminalType=Iphone&cid=213"]];
    [dataTask resume];
}
//接收請(qǐng)求頭
- (void)URLSession:(NSURLSession *)session dataTask:(NSURLSessionDataTask *)dataTask didReceiveResponse:(nonnull NSURLResponse *)response completionHandler:(nonnull void (^)(NSURLSessionResponseDisposition))completionHandler
{
    //允許處理服務(wù)器的響應(yīng),才會(huì)繼續(xù)接受服務(wù)器返回的數(shù)據(jù)
    completionHandler(NSURLSessionResponseAllow);
}
//接收數(shù)據(jù)
- (void)URLSession:(NSURLSession *)session dataTask:(NSURLSessionDataTask *)dataTask didReceiveData:(NSData *)data
{
    [self.data appendData:data];
}
//結(jié)束接收數(shù)據(jù)或者出錯(cuò)
- (void)URLSession:(NSURLSession *)session task:(NSURLSessionTask *)task didCompleteWithError:(NSError *)error
{
    if (!error) {
        id json  = [NSJSONSerialization JSONObjectWithData:self.data options:NSJSONReadingAllowFragments error:nil];
        NSLog(@"%@",json);
    }
}
  • 發(fā)送異步的post請(qǐng)求(block)并解析數(shù)據(jù)
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:@"http://ipad-bjwb.bjd.com.cn/DigitalPublication/publish/Handler/APINewsList.ashx"]];
    //設(shè)置請(qǐng)求方法
    request.HTTPMethod = @"POST";
    request.HTTPBody = [@"date=20151101&startRecord=1&len=5&udid=1234567890&terminalType=Iphone&cid=213" dataUsingEncoding:NSUTF8StringEncoding];
    //初始化
    NSURLSession  *session = [NSURLSession sharedSession];
    //創(chuàng)建任務(wù)
    NSURLSessionDataTask *datatask = [session dataTaskWithRequest:request completionHandler:^(NSData * _Nullable data, NSURLResponse * _Nullable response, NSError * _Nullable error) {
        //解析數(shù)據(jù)
        id json = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingAllowFragments error:nil];
        NSLog(@"%@",json);
    }];
//    開(kāi)啟
    [datatask resume];
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書(shū)系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

推薦閱讀更多精彩內(nèi)容