Ios之網路編程NSURLConnection,iosnsurlconnection

來源:互聯網
上載者:User

Ios之網路編程NSURLConnection,iosnsurlconnection

  通過NSURLConnection主要通過四個類進行網路訪問:NSURL,NSURLRequest,NSMutableURLRequest,NSURLConnection

  一、基本知識

(1)NSURL:請求地址

(2)NSURLRequest:封裝一個請求,儲存發給伺服器的全部資料,包括一個NSURL對象,要求方法、要求標頭、請求體....

(3)NSMutableURLRequest:NSURLRequest的子類

(4)NSURLConnection:負責發送請求,建立用戶端和伺服器的串連。發送NSURLRequest的資料給伺服器,並收集來自伺服器的響應資料

  二、功能實現

  1、/*******get方式*******/

//全域變數,接收資料NSMutableData * requestData;NSURL * url=[NSURL URLWithString:@"http://192.168.2.162/logo.php?userName=jereh&pwd=123"];//通過URL建立請求NSURLRequest * request=[NSURLRequest requestWithURL:url];//通過NSURLConnection串連伺服器,並發送請求NSURLConnection * connection=[NSURLConnection connectionWithRequest:request delegate:self];[connection start];//接收到請求- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response{NSLog(@"didReceiveResponse");//在該方法中初始化datarequestData=[NSMutableData data];}//收到資料- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data{//防止檔案過大,多次追加[requestData appendData:data];}//資料接收完畢- (void)connectionDidFinishLoading:(NSURLConnection *)connection{NSDictionary * dic=[NSJSONSerialization JSONObjectWithData:requestData options:NSJSONReadingAllowFragments error:nil];NSLog(@"%@",dic);}//傳輸失敗- (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error{NSLog(@"didFailWithError");}

2、/******post方式*******/

NSURL * url=[NSURL URLWithString:@"http://192.168.2.162/loginPost.php"];//定義可變的請求NSMutableURLRequest * request=[NSMutableURLRequest requestWithURL:url];//佈建要求方式request.HTTPMethod=@"POST";//佈建要求參數request.HTTPBody=[@"userName=jereh&pwd=123" dataUsingEncoding:NSUTF8StringEncoding];NSURLConnection * con=[NSURLConnection connectionWithRequest:request delegate:self];[con start];

3、非代理方法

//同步NSURLResponse * response;NSData *  data=[NSURLConnection sendSynchronousRequest:request returningResponse: &response error:nil];//非同步[NSURLConnection sendAsynchronousRequest:request queue:[NSOperationQueue mainQueue] completionHandler:^(NSURLResponse *response, NSData *data, NSError *connectionError) {//主線程操作}];

 

作者:傑瑞教育
出處:http://www.cnblogs.com/jerehedu/ 
著作權聲明:本文著作權歸煙台傑瑞教育科技有限公司和部落格園共有,歡迎轉載,但未經作者同意必須保留此段聲明,且在文章頁面明顯位置給出原文串連,否則保留追究法律責任的權利。
技術諮詢: 

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.