IOS 網路請求

來源:互聯網
上載者:User

標籤:

 

技術交流新QQ群:414971585

 

關於網路請求的重要性我想不用多說了吧。對於移動用戶端來說,網路的重要性不言而喻。常見的網路請求有同步GET, 同步POST, 非同步GET, 非同步POST。今天來看一下四種網路請求的實現方式。

一、同步GET

123456789101112 // 1.將網址初始化成一個OC字串對象NSString *urlStr = [NSString stringWithFormat:@"%@?query=%@®ion=%@&output=json&ak=6E823f587c95f0148c19993539b99295", kBusinessInfoURL, @"銀行", @"濟南"];// 如果網址中存在中文,進行URLEncodeNSString *newUrlStr = [urlStr stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];// 2.構建網路URL對象, NSURLNSURL *url = [NSURL URLWithString:newUrlStr];// 3.建立網路請求NSURLRequest *request = [NSURLRequest requestWithURL:url cachePolicy:NSURLRequestReloadIgnoringLocalCacheData timeoutInterval:10];// 建立同步連結NSURLResponse *response = nil;NSError *error = nil;NSData *data = [NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&error];

當建立好同步連結以後, 就可以採用相應的方法進行解析。下面建立非同步串連也是一樣的。

二、同步POST

1234567891011121314151617 // 1.根據網址初始化OC字串對象    NSString *urlStr = [NSString stringWithFormat:@"%@", kVideoURL];    // 2.建立NSURL對象    NSURL *url = [NSURL URLWithString:urlStr];    // 3.建立請求    NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];    // 4.建立參數字串對象    NSString *parmStr = @"method=album.channel.get&appKey=myKey&format=json&channel=t&pageNo=1&pageSize=10";    // 5.將字串轉為NSData對象    NSData *pramData = [parmStr dataUsingEncoding:NSUTF8StringEncoding];    // 6.佈建要求體    [request setHTTPBody:pramData];    // 7.佈建要求方式    [request setHTTPMethod:@"POST"];         // 建立同步連結    NSData *data = [NSURLConnection sendSynchronousRequest:request returningResponse:nil error:nil];

三、非同步GET

1234567891011     NSString *urlStr = [NSString stringWithFormat:@"http://image.zcool.com.cn/56/13/1308200901454.jpg"];    NSString *newStr = [urlStr stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];    NSURL *url = [NSURL URLWithString:newStr];    NSURLRequest *requst = [NSURLRequest requestWithURL:url cachePolicy:NSURLRequestReloadIgnoringLocalCacheData timeoutInterval:10];    //非同步連結(形式1,較少用)    [NSURLConnection sendAsynchronousRequest:requst queue:[NSOperationQueue mainQueue] completionHandler:^(NSURLResponse *response, NSData *data, NSError *connectionError) {        self.imageView.image = [UIImage imageWithData:data];        // 解析        NSDictionary *dic = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:nil];        NSLog(@"%@", dic);    }];

四、非同步POST

1234567891011121314 // POST請求    NSString *urlString = [NSString stringWithFormat:@"%@",kVideoURL];    //建立url對象    NSURL *url = [NSURL URLWithString:urlString];    //建立請求    NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url cachePolicy:NSURLRequestReloadIgnoringLocalCacheData timeoutInterval:10];    //建立參數字串對象    NSString *parmStr = [NSString stringWithFormat:@"method=album.channel.get&appKey=myKey&format=json&channel=t&pageNo=1&pageSize=10"];    //將字串轉換為NSData對象    NSData *data = [parmStr dataUsingEncoding:NSUTF8StringEncoding];    [request setHTTPBody:data];    [request setHTTPMethod:@"POST"];    //建立非同步串連(形式二)    [NSURLConnection connectionWithRequest:request delegate:self];

一般的,當建立非同步串連時, 很少用到第一種方式,經常使用的是代理方法。關於NSURLConnectionDataDelegate,我們經常使用的協議方法為一下幾個:

1234567891011121314151617 // 伺服器接收到請求時- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response{}// 當收到伺服器返回的資料時觸發, 返回的可能是資源片段- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data{}// 當伺服器返回所有資料時觸發, 資料返回完畢- (void)connectionDidFinishLoading:(NSURLConnection *)connection{}// 請求資料失敗時觸發- (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error{    NSLog(@"%s", __FUNCTION__);}

最後,分析一下這幾種呢網路請求的區別。

GET請求和POST請求的區別:

1. GET請求的介面會包含參數部分,參數會作為網址的一部分,伺服器位址與參數之間通過 ? 來間隔。POST請求會將伺服器位址與參數分開,請求介面中只有伺服器位址,而參數會作為請求的一部分,提交後台伺服器。

2. GET請求參數會出現在介面中,不安全。而POST請求相對安全。

3.雖然GET請求和POST請求都可以用來請求和提交資料,但是一般的GET多用於從後台請求資料,POST多用於向後台提交資料。

同步和非同步區別:

同步連結:主線程去請求資料,當資料請求完畢之前,其他線程一律不響應,會造成程式就假死現象。

非同步連結:會單獨開一個線程去處理網路請求,主線程依然處於可互動狀態,程式運行流暢。

 

原文源自:http://www.cocoachina.com/ios/20140919/9691.html

IOS 網路請求

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.