在网上找了很久,一直没找到很详细的,自己试了很多次终于可以了,现在写下来,希望能对大家有帮助。
NSURLConnection异步GET请求:
第一步:
让类实现这两个接口:
NSURLConnectionDelegate,NSURLConnectionDataDelegate
第二步:
实现接口对应的方法:
-(void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response{
NSInteger code=[(NSHTTPURLResponse*)response statusCode];
NSLog(@"didReceiveResponse....code=%d",code);
}
-(void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error{
NSLog(@"didFailWithError...%@",[error description]);
}
-(void)connectionDidFinishLoading:(NSURLConnection *)connection{
NSLog(@"connectionDidFinishLoading....");
}
-(void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data{
NSString *str=[[NSString alloc]initWithData:data encoding:NSASCIIStringEncoding];
NSLog(@"didReceiveData....data=%@",str);
}
第三步:
设置NSMutableURLRequest和发起请求:
NSString *strUrl=[NSString stringWithFormat:@" 你的地址"];
NSURL *url=[NSURL URLWithString:strUrl];
NSMutableURLRequest *request=[[NSMutableURLRequest alloc]initWithURL:url cachePolicy:NSURLRequestReloadIgnoringCacheData timeoutInterval:20];
[request setHTTPMethod:@"GET"];
[request setValue:@"application/x-www-form-urlencoded" forHTTPHeaderField:@"Content-Type"];//这个很关键,一定要设置
[request setValue:@"字段对应的值1" forHTTPHeaderField:@"你头部的字段1"];//这里就是你自己对应的参数
[request setValue:@"字段对应的值2" forHTTPHeaderField:@"你头部的字段2"];//这里就是你自己对应的参数
mConn=[[NSURLConnection alloc]initWithRequest:request delegate:self startImmediately:true];
[mConn start];