詳談iPhone中網路請求

來源:互聯網
上載者:User

詳談iPhone網路請求是本文要介紹的內容,主要介紹了網路編程的相關內容,很詳細的介紹了如何獲得或者發送網路請求。不多說,我們先來看詳細內容。

一、簡單的get請求

網路編程是我們經常遇到的,在IPhone中,SDK提供了良好的介面,主要使用的類有NSURL,NSMutableURLRequest,NSURLConnection等等。一般情況下建議使用非同步接收資料的方式來請求網路連接,這種網路連接分為兩步,第一步是建立NSURLConnection對象後,直接調用它的start方法來串連網路。第二步是使用delegate方式來接收資料,這裡給一個常用的寫法:

網路請求部分:

 
  1. NSString *urlString = [NSString stringWithFormat:@"http://www.voland.com.cn:8080/weather/weatherServlet?city=%@",kcityID];  
  2. NSURL *url = [NSURL URLWithString:urlString];  
  3. NSMutableURLRequest *request = [NSMutableURLRequest  requestWithURL:url];  
  4. NSURLConnection *aUrlConnection = [[NSURLConnection alloc] initWithRequest:request delegate:self startImmediately:true];  
  5. self.urlConnection = aUrlConnection;//這裡的urlConnection在標頭檔中定義的變數  
  6. [self.urlConnection start];//開始串連網路  
  7. [aUrlConnection release];  
  8. [[UIApplication sharedApplication] setNetworkActivityIndicatorVisible:YES]; 

接收資料部分,接收到的資料主要是在這裡處理

 
  1. - (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response  {  
  2. NSLog(@"接收完響應:%@",response);  
  3. }  
  4. - (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data  {  
  5. NSLog(@"接收完資料:");  
  6. }  
  7. - (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error  {  
  8. NSLog(@"資料接收錯誤:%@",error);  
  9. }  
  10. - (void)connectionDidFinishLoading:(NSURLConnection *)connection  {  
  11. NSLog(@"串連完成:%@",connection);  
  12. [[UIApplication sharedApplication] setNetworkActivityIndicatorVisible:NO];  

二、Post請求

進行post請求,主要是設定好NSMutableURLRequest對象,在get請求中,我們都使用了預設的,實際這些request內容都可以設定的。設定好後,其它與get方式同:

 
  1. NSString *content=[[NSString alloc] initWithData: data encoding: NSUTF8StringEncoding];  
  2. [request setHTTPBody: content];    
  3. [request setHTTPMethod: @"POST"];    
  4. [request setValue:@"Close" forHTTPHeaderField:@"Connection"];    
  5. [request setValue:@"www.voland.com.cn" forHTTPHeaderField:@"Host"];    
  6. [request setValue:[NSString stirngWithFormat@"%d",[content length]] forHTTPHeaderField:@"Content-Length"]; 

小結:詳談iPhone網路請求的內容介紹完了,希望本文對你有所協助!

相關文章

聯繫我們

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