1. 程式人生 > >IOS網路程式設計 HTTP

IOS網路程式設計 HTTP

HTTP定義了一種在伺服器和客戶端之間傳遞資料的途徑。

 

URL定義了一種唯一標示資源在網路中位置的途徑。

   

REQUESTS 和 RESPONSES:

 

客戶端先建立一個TCP連線,然後傳送一個請求。伺服器受到請求處理後傳送一個響應向客戶端傳遞資料。然後客戶端可以繼續傳送請求或者關閉這個TCP連線。

 

HTTPS:
在TCP連線建立後,傳送請求之前,需要建立一個一個SSL會話。

 

request方法和它們的用途

 

   

注意:想server傳送大量資料需要用POST,因為GET僅支援傳送少量資料(8KB)。

   

iOS的NSURLRequest和它的子類NSMutableURLRequest提供了建立HTTP請求的方法。

 

NSURLResponse 和 它的子類NSHTTPURLResponse 處理返回的資料。

 

URL:

 

   

Protocol包括HTTP、FTP和file。

 

URL編碼:

    
NSString *urlString = @"http://myhost.com?query=This is a question"; 
NSString *encoded = [urlString stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
   

NSURL用來管理URL。

   

IOS HTTP APIS:

 

涉及到下面一些類:

 

NSURL, NSURLRequest, NSURLConnection, 和 NSURLResponse.

 

1、NSURL

 

NSURL可以定義本地檔案和網路檔案

    
NSURL *url = [NSURL urlWithString:@"http://www.google.com"]; 
  
NSData *data = [NSData dataWithContentsOfURL:url];
   

NSURL定義了很多訪問器:

    
if (url.port == nil) { 
  NSLog(@"Port is nil");} else {  NSLog(@"Port is not nil
");}
   

2、NSURLRequest

 

建立了NSURL後,就可以用NSURLRequest建立請求了:

    
NSURL *url = [NSURL URLWithString: @"https://gdata.youtube.com/feeds/api/standardfeeds/top_rated"];if (url == nil) {     NSLog(@"Invalid URL"); 

   return;}NSURLRequest *request = [NSURLRequest requestWithURL:url];

if (request == nil) {  NSLog(@"Invalid Request");    return; }
   

NSMutableURLRequest是NSURLRequest 的子類,提供了改變請求的屬性的方法:

    
NSURL *url = [NSURL urlWithString@"http://server.com/postme"]; 
NSMutableURLRequest *req = [NSMutableURLRequest requestWithURL:url];
[req setHTTPMethod:@"POST"];[req setHTTPBody:[@"Post body" dataUsingEncoding:NSUTF8StringEncoding]];
   

如果你要傳送一個圖片或者視訊,那麼用需要用NSInputStream,它沒有把資料全部加在到記憶體。

    
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];NSInputStream *inStream = [NSInputStream inputStreamWithFileAtPath:srcFilePath];[request setHTTPBodyStream:inStream];[request setHTTPMethod:@"POST"];
     

3、NSURLResponse

     

4、NSURLConnection

 

提供了初始化、開始、和取消一個連線。

 

傳送同步請求:

    
- (NSArray *) doSyncRequest:(NSString *)urlString {    // make the NSURL object from the string    NSURL *url = [NSURL URLWithString:urlString];        // Create the request object with a 30 second timeout and a cache policy to always retrieve the    // feed regardless of cachability.    NSURLRequest *request =        [NSURLRequest requestWithURL:url                         cachePolicy:NSURLRequestReloadIgnoringLocalAndRemoteCacheData                     timeoutInterval:30.0];        // Send the request and wait for a response    NSHTTPURLResponse   *response;    NSError             *error;    NSData *data = [NSURLConnection sendSynchronousRequest:request                                          returningResponse:&response                                                      error:&error];    // check for an error    if (error != nil) {        NSLog(@"Error on load = %@", [error localizedDescription]);        return nil;    }        // check the HTTP status    if ([response isKindOfClass:[NSHTTPURLResponse class]]) {        NSHTTPURLResponse *httpResponse = (NSHTTPURLResponse *)response;        if (httpResponse.statusCode != 200) {            return nil;        }        NSLog(@"Headers: %@", [httpResponse allHeaderFields]);    }        // Parse the data returned into an NSDictionary    NSDictionary *dictionary =         [XMLReader dictionaryForXMLData:data                                   error:&error];    // Dump the dictionary to the log file    NSLog(@"feed = %@", dictionary);        NSArray *entries =[self getEntriesArray:dictionary];        // return the list if items from the feed.    return entries;}
       

Queued Asynchronous Requests:

    
- (void) doQueuedRequest:(NSString *)urlString  delegate:(id)delegate {    // make the NSURL object    NSURL *url = [NSURL URLWithString:urlString];        // create the request object with a no cache policy and a 30 second timeout.    NSURLRequest *request = [NSURLRequest requestWithURL:url cachePolicy:NSURLRequestReloadIgnoringLocalAndRemoteCacheData timeoutInterval:30.0];        // If the queue doesn't exist, create one.    if (queue == nil) {        queue = [[NSOperationQueue alloc] init];    }        // send the request and specify the code to execute when the request completes or fails.    [NSURLConnection sendAsynchronousRequest:request                                        queue:queue                            completionHandler:^(NSURLResponse *response,                                                NSData *data,                                                NSError *error) {                                           if (error != nil) {               NSLog(@"Error on load = %@", [error localizedDescription]);            } else {                                // check the HTTP status                if ([response isKindOfClass:[NSHTTPURLResponse class]]) {                    NSHTTPURLResponse *httpResponse = (NSHTTPURLResponse *)response;                    if (httpResponse.statusCode != 200) {                        return;                    }                    NSLog(@"Headers: %@", [httpResponse allHeaderFields]);                }                                               // parse the results and make a dictionary                NSDictionary *dictionary =                    [XMLReader dictionaryForXMLData:data                                              error:&error];                NSLog(@"feed = %@", dictionary);                // get the dictionary entries.                NSArray *entries =[self getEntriesArray:dictionary];                // call the delegate                if ([delegate respondsToSelector:@selector(setVideos:)]) {                    [delegate performSelectorOnMainThread:@selector(setVideos:)                                                withObject:entries                                             waitUntilDone:YES];                }            }    }];}
     

NSURLConnection start方法和Delegate:

 

 

GET:

    
 NSURL  *url=[[ NSURL   alloc ] initWithString :urlString];     NSMutableURLRequest  *request=[[NSMutableURLRequest  alloc ] init ];     NSURLConnection  *connection = [[ NSURLConnection   alloc ]  initWithRequest :request delegate : self ];     if (connection)     {             [connection start];         }     else     {             NSLog ( @"sorry" );     }/** NSURLConnectionDataDelegate*/- (void)connection:(NSURLConnection*)connection didReceiveResponse:(NSURLResponse *)response{
  [activityIndicator startAnimating]; //UIActivityIndicatorView    NSLog(
@"Did Receive Response %@", response);    responseData = [[NSMutableData alloc]init];}- (void)connection:(NSURLConnection*)connection didReceiveData:(NSData*)data{    //NSLog(@"Did Receive Data %@", data);    [responseData appendData:data]; //NSMutableData}- (void)connection:(NSURLConnection*)connection didFailWithError:(NSError*)error{    NSLog(@"Did Fail");}- (void)connectionDidFinishLoading:(NSURLConnection *)connection{
  

[activityIndicator stopAnimating];

  
    NSLog(@"Did Finish");    // Do something with responseData}
   

POST:

    
//initialize new mutable data    NSMutableData *data = [[NSMutableData alloc] init];    self.receivedData = data;        //initialize url that is going to be fetched.    NSURL *url = [NSURL URLWithString:@"http://www.snee.com/xml/crud/posttest.cgi"];        //initialize a request from url    NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:[url standardizedURL]];        //set http method    [request setHTTPMethod:@"POST"];    //initialize a post data    NSString *postData = [[NSString alloc] initWithString:@"fname=example&lname=example"];    //set request content type we MUST set this value.        [request setValue:@"application/x-www-form-urlencoded; charset=utf-8" forHTTPHeaderField:@"Content-Type"];        //set post data of request    [request setHTTPBody:[postData dataUsingEncoding:NSUTF8StringEncoding]];        //initialize a connection from request    NSURLConnection *connection = [[NSURLConnection alloc] initWithRequest:request delegate:self];    self.connection = connection;    //start the connection    [connection start];
   

 非同步請求:
非同步請求需要一個run loop來操作代理物件,GCD和NSOperationQueue預設並沒有run loop,所以如果你想在後臺發起一個HTTP請求,必須確保有run loop。

    
NSURLConnection connection = [[NSURLConnection alloc] initWithRequest:requestdelegate:self startImmediately:NO];[connection scheduleInRunLoop:[NSRunLoop mainRunLoop] forMode:NSDefaultRunLoopMode];[connection start];
   

上面的程式碼是在主執行緒執行,如果想在其他執行緒執行,可以在其他執行緒新建一個run loop,並繫結到connection。