您的位置:首页 > 理论基础 > 计算机网络

IOS开发—网络请求之GET/POST同步请求

2015-03-19 09:11 477 查看

网络请求之GET/POST同步请求

同步请求的特点:发送同步请求的时候,无法与应用进行交互。

发送同步请求的方法:

+ (NSData *)sendSynchronousRequest:(NSURLRequest *)requestreturningResponse:(NSURLResponse **)response error:(NSError **)error;


代码实例:

#import "LXXViewController.h"
#define URL_WITH_PARAM @"http://kaiyi.3tichina.com:8001/mall/list.php?page=1&catid=4";
#define URL_WITHOUT_PARAM @"http://kaiyi.3tichina.com:8001/mall/list.php";
#define PARAM @"page=1&catid=4";
@interface LXXViewController ()
@property (weak,nonatomic) IBOutletUIImageView *imageView;
@property (weak,nonatomic) IBOutletUIButton *loadButton;
 
@property (strong,nonatomic) NSMutableURLRequest *request;
@property (copy,nonatomic) NSString *imgURLString;
@property (strong,nonatomic) NSData *responseData;
@end
 
@implementationLXXViewController
 
- (void)viewDidLoad
{
    [super viewDidLoad];
    self.title =@"网络请求Demo";
    //设置请求
    [self setRequest];
}
 
#pragma mark - setRequest
- (void)setRequest
{
    //get同步请求
    NSString *str = URL_WITH_PARAM;
    NSURL *URL = [NSURLURLWithString:str];
    _request = [NSMutableURLRequestrequestWithURL:URL];
    _responseData = [NSURLConnectionsendSynchronousRequest:_requestreturningResponse:nilerror:nil];
   
    //post同步请求
//    NSString *str = URL_WITHOUT_PARAM;
//    NSURL *URL = [NSURL URLWithString:str];
//    _request = [NSMutableURLRequestrequestWithURL:URL];
//    [_request setHTTPMethod:@"POST"];
//    NSString *param = PARAM;
//    NSData *data = [paramdataUsingEncoding:NSUTF8StringEncoding];
//    //设置请求提(参数)
//    [_request setHTTPBody:data];
//    _responseData = [NSURLConnectionsendSynchronousRequest:_request returningResponse:nil error:nil];
}
 
- (IBAction)loadAction:(id)sender
{
    //下面代码不是本文关键
    //解析请求响应数据,获取到响应数据中的一个图像URL,再次请求显示在imageView出来,以放大请求结果。
    NSDictionary *dic = [NSJSONSerializationJSONObjectWithData:_responseDataoptions:NSJSONReadingMutableLeaveserror:nil];
    NSArray *arr = [dic objectForKey:@"data"];
    NSDictionary *dicData = [arrobjectAtIndex:0];
    _imgURLString = [dicData objectForKey:@"thumb"];
    NSURL *imageURL = [NSURLURLWithString:_imgURLString];
    NSURLRequest *request = [[NSURLRequestalloc]initWithURL:imageURLcachePolicy:NSURLRequestReloadIgnoringLocalCacheDatatimeoutInterval:10.0];
       NSData *data = [NSURLConnectionsendSynchronousRequest:request returningResponse:nil error:nil];
    UIImage *image = [UIImageimageWithData:data];
    _imageView.image = image;
}
@end


点击button后的界面效果:(从网络上加载出了指定图像)

内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: