- (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");
}