标签:
#pragma mark请求文本
- (IBAction)getRemoteText:(UIButton *)sender {
//1.创建url对象
// NSURL *url=[NSURL URLWithString:@"http://api.hudong.com/iphonexml.do?type=focus-c"];
/*其中缓存策略是个枚举类型包含:
NSURLRequestUseProtocolCachePolicy(基础策略,一般使用此策略)
NSURLRequestReloadIgnoringLocalCacheData(忽略本地缓存)
NSURLRequestReturnCacheDataElseLoad(首先使用缓存,如果没有本地缓存,才从原地址下载)
NSURLRequestReturnCacheDataDontLoad(使用本地缓存,从不下载,如果本地没有缓存,则请求失败,此策略多用于离线操作)
NSURLRequestReloadIgnoringLocalAndRemoteCacheData(无视任何缓存策略,无论是本地的还是远程的,总是从原地址重新下载)
NSURLRequestReloadRevalidatingCacheData(验证本地数据与远程数据是否相同,如果不同则下载远程数据,否则使用本地数据。)*/
//2.创建
// NSURLRequest *request =[NSURLRequest requestWithURL:url cachePolicy: (NSURLRequestUseProtocolCachePolicy) timeoutInterval:10.0f];
//3.使用connection发送同步请求对象
// NSURLResponse *response;
// NSError *error;
// NSData *data=[NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&error];
// if (error !=nil) {
// NSLog(@"error:%@",[error localizedDescription]);
// }else{
// NSLog(@"error:%@",response);
// NSString *str =[[NSString alloc]initWithData:data encoding:NSUTF8StringEncoding];
// self.textView.text=str;
// }
//HTTP的post方式请求
//1.创建URL方式请求
NSURL *url=[NSURL URLWithString:@"http://api.hudong.com/iphonexml.do"];
//2.创建request对象
NSMutableURLRequest *request=[NSMutableURLRequest requestWithURL:url cachePolicy:NSURLRequestUseProtocolCachePolicy timeoutInterval:10.0f];
//指定HTTP为post方式
[request setHTTPMethod:@"POST"];
//打包请求参数
NSString *requestStr=[NSString stringWithFormat:@"type=%@",@"focus-c"];
NSData *requestData=[requestStr dataUsingEncoding:NSUTF8StringEncoding];
//设置HTTP请求的数据报
[request setHTTPBody:requestData];
//3.使用connection发送同步请求对象
NSURLResponse *response;
NSError *error;
NSData *data=[NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&error];
if (error !=nil) {
NSLog(@"error:%@",[error localizedDescription]);
}else{
NSLog(@"error:%@",response);
NSString *str =[[NSString alloc]initWithData:data encoding:NSUTF8StringEncoding];
self.textView.text=str;
}
}
#pragma mark 请求图片
- (IBAction)getRemoteImage:(UIButton *)sender {
//1.创建url对象
NSURL *url=[NSURL URLWithString:@"http://pic.nipic.com/2007-11-09/2007119122519868_2.jpg"];
//2.创建
NSURLRequest *request =[NSURLRequest requestWithURL:url cachePolicy: (NSURLRequestUseProtocolCachePolicy) timeoutInterval:10.0f];
//3.使用connection对象发送异步请求
[NSURLConnection sendAsynchronousRequest:request queue:[NSOperationQueue new] completionHandler:^(NSURLResponse *response, NSData *data, NSError *connectionError) {
if(connectionError != nil){
NSLog(@"error:%@",[connectionError localizedDescription]);
}else{
//更新
//使用GCD获取主线程,在主线程中更新UI
// 更新UI一定要在主线程中更新
// 使用GCD获取主线程,在主线程中更新UI
dispatch_async(dispatch_get_main_queue(), ^{
self.imageView.image = [UIImage imageWithData:data];
});
}
}];
}
标签:
原文地址:http://www.cnblogs.com/SanyeCaoAlone/p/4997040.html