異步post例子(Meal4me登陸)

- (void)requestLoginWithUser:(NSString *)userName andPassword:(NSString *)passWord;

{

    //封裝參數

    NSString *post = nil;  

    post = [[[NSString alloc] initWithFormat:@"username=%@&password=%@",userName, passWord]autorelease];

    //把參數封裝在NSData中

    NSData *postData = [post dataUsingEncoding:NSASCIIStringEncoding allowLossyConversion:YES];  

    //NSData的Length

    NSString *postLength = [NSString stringWithFormat:@"%d", [postData length]];  

    //實例化Request對象

    NSMutableURLRequest *_request = [[NSMutableURLRequest alloc] init]; 

    [self initURLRequest:_request WithHost:host andAnother:login];

    //設置Request

    [_request setValue:postLength forHTTPHeaderField:@"Content-Length"];

    [_request setHTTPBody:postData];

    //用該Request對象實例化一個Connection

    NSURLConnection *connection = [NSURLConnection connectionWithRequest:_request delegate:self];

    [self.connectionArray replaceObjectAtIndex:M4MHttpRequestTypeLogin withObject:connection];

    

    [_request release];  

}

//再實現4個協議函數處理接受數據

- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response {

    // store data

    // [self.receivedData setLength:0];            //通常在這裏先清空接受數據的緩存

    NSLog(@"responce");

    

}


- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data {

    /* appends the new data to the received data */

    //可能多次收到數據,把新的數據添加在現有數據最後

    NSLog(@"data");

    if ( data != nil )

    {

        NSString *str = [[NSStringalloc] initWithData:data encoding:NSUTF8StringEncoding];

        NSLog(@"%@", str);

    }

}


- (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error {

    // 錯誤處理

    NSLog(@"error");

}


- (void)connectionDidFinishLoading:(NSURLConnection *)connection {

    // disconnect

    [UIApplication sharedApplication].networkActivityIndicatorVisible =NO;   

   // NSString *returnString = [[NSString alloc] initWithData:self.receivedData encoding:NSUTF8StringEncoding];

   // NSLog(returnString);

   // [self urlLoaded:[self urlString] data:self.receivedData];

   //firstTimeDownloaded = YES;

    NSLog(@"finish");

}


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章