异步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");

}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值