iPhone應用用HTTP協議和伺服器通訊

來源:互聯網
上載者:User

iPhone應用HTTP協議伺服器通訊是本文要介紹的內容,主要是來學習iphone應用中的通訊協定,具體內容來看本文詳解。

iPhone用http協議和伺服器通訊有兩種方式,一種是同步一種是非同步,所謂同步是指當用戶端調用post/get的方式的函數向伺服器發出資料請求後,該函數不會直接返回,只有得到伺服器響應或者請求時間timeout之後才會返回繼續執行其它任務。非同步採用回調的方式,即請求發送後,函數會立即返回,一旦伺服器連接成功作業系統會去觸發相應的回調進行相應的處理。這和window的訊息處理機制一樣。

同步一般用於一次性操作,如判斷當前網路是否可用等等。多的就不再一一介紹,在實現上面有兩點不同:

(1)在用NSURLConnect的時候一個調用同步函數一個調用了非同步函數。

(2)非同步需要實現delegate的相關回呼函數。

以下是參考代碼:

同步方式:

 
  1. -(void)UpadaPost:(NSString *)strcontext URL:(NSString *)urlstr{  
  2. NSLog(urlstr);  
  3. NSLog(strcontext);  
  4. assert(strcontext != NULL);  
  5. assert(urlstr != NULL);  
  6. NSData*postData=[strcontextdataUsingEncoding:NSASCIIStringEncoding  allowLossyConversion:YES];   
  7. NSString *postLength = [NSString stringWithFormat:@"%d", [postData length]];   
  8. NSMutableURLRequest *request = [[[NSMutableURLRequest alloc] init] autorelease];   
  9. [request setURL:[NSURL URLWithString:urlstr]];   
  10. [request setHTTPMethod:@"POST"]; [request setTimeoutInterval: 20];//setting timeout  
  11. [request setValue:postLength forHTTPHeaderField:@"Content-Length"];   
  12. [request setValue:@"application/x-www-form-urlencoded" forHTTPHeaderField:@"Content-Type"];   
  13. [request setHTTPBody:postData];   
  14. NSURLResponse *respone;  
  15. NSError *error;  
  16. NSData*myReturn=[NSURLConnection  sendSynchronousRequest:request returningResponse:&respone  
  17. error:error];  
  18. NSLog(@"%@", [[NSString alloc] initWithData:myReturn encoding:NSUTF8StringEncoding]);  

非同步方式:

 
  1. -(void)UpadaPost:(NSString *)strcontext URL:(NSString *)urlstr{  
  2. NSLog(urlstr);  
  3. NSLog(strcontext);  
  4. assert(strcontext != NULL);  
  5. assert(urlstr != NULL);  
  6. NSData *postData = [strcontext dataUsingEncoding:NSASCIIStringEncoding  allowLossyConversion:YES];   
  7. NSString *postLength = [NSString stringWithFormat:@"%d", [postData length]];   
  8. NSMutableURLRequest *request = [[[NSMutableURLRequest alloc] init] autorelease];   
  9. [request setURL:[NSURL URLWithString:urlstr]];   
  10. [request setHTTPMethod:@"POST"]; [request setTimeoutInterval: 20];//setting timeout  
  11. [request setValue:postLength forHTTPHeaderField:@"Content-Length"];   
  12. [request setValue:@"application/x-www-form-urlencoded"  forHTTPHeaderField:@"Content-Type"];   
  13. [request setHTTPBody:postData];   
  14. NSURLConnection *conn=[[NSURLConnection alloc] initWithRequest:request  delegate:self];   
  15. if (conn)     
  16. {   
  17. NSLog(@"Connection success");  
  18. [UIApplication sharedApplication].networkActivityIndicatorVisible = YES;  
  19. [conn retain];  
  20. }     
  21. else     
  22. {   
  23. // inform the user that the download could not be made   
  24. }   
  25. }  
  26. #pargma mark 

以下為相應的回呼函數

 
  1. // 收到響應時, 會觸發  
  2. - (void)connection:(NSURLConnection *)connection   didReceiveResponse:(NSURLResponse *)response  {  
  3. // 注意這裡將NSURLResponse對象轉換成NSHTTPURLResponse對象才能去  
  4. NSHTTPURLResponse *httpResponse = (NSHTTPURLResponse*)response;  
  5. if ([response respondsToSelector:@selector(allHeaderFields)]) {  
  6. NSDictionary *dictionary = [httpResponse allHeaderFields];  
  7. NSLog([dictionary description]);  
  8. NSLog(@"%d",[response statusCode]);  
  9. }  
  10. }  
  11. //連結錯誤    
  12. - (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error {  
  13. //[self performSelectorOnMainThread:@selector(httpConnectEnd) withObject:nil  waitUntilDone:NO];  
  14. NSLog(@"%@",[error localizedDescription]);  
  15. }  
  16. // Called when a chunk of data has been downloaded.  
  17. //接收資料 每收到一次資料, 會調用一次  
  18. - (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data {  
  19. // Process the downloaded chunk of data.  
  20. NSLog(@"%d", [data length]);  
  21. //NSLog(@"%@", [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding]);  
  22. //[self performSelectorOnMainThread:@selector(updateProgress) withObject:nil  waitUntilDone:NO];  
  23. }  
  24. //接收結束  
  25. - (void)connectionDidFinishLoading:(NSURLConnection *)connection {  
  26. NSLog(@"%@",connection);  
  27. //NSLog(@"%lld", received_);  
  28. //[self performSelectorOnMainThread:@selector(httpConnectEnd) withObject:nil  waitUntilDone:NO];  
  29. // Set the condition which ends the run loop.  

小結:iPhone應用HTTP協議伺服器通訊的內容介紹完了,希望通過本文的學習能對你有所協助!

聯繫我們

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