网络请求的两种方式:GET 和 POST
1.普通封装方法:封装到一个类中
1、自定义一个block
typedefvoid (^DataBlock) (id data);
2、自定义GET 、POST方法
+ (void)getDataByURLString:(NSString *)urlString WithDataBlock:(DataBlock)dataBlock;
+ (void)getDataByURLString:(NSString *)urlString HttpMethod:(NSString *)method BodyString:(NSString *)bodyString DataBlock:(DataBlock)datablock;
3、实现GET、POST方法
+ (void)getDataByURLString:(NSString *)urlString WithDataBlock:( DataBlock)dataBlock{
NSURL *url = [NSURL URLWithString:urlString];
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];
[NSURLConnection sendAsynchronousRequest:request queue:[NSOperationQueue mainQueue] completionHandler:^(NSURLResponse *response, NSData *data, NSError *connectionError) {
dataBlock(data);
}];
}
+ (void)getDataByURLString:(NSString *)urlString HttpMethod:(NSString *)method BodyString:(NSString *)bodyString DataBlock:(DataBlock)datablock{
urlString = [urlString stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
NSURL *url = [NSURL URLWithString:urlString];
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];
//默认是get方法,修改成post
if ([method isEqual:@"POST"]) {
[request setHTTPMethod:method];
NSData *bodyData = [bodyString dataUsingEncoding:NSUTF8StringEncoding];
[request setHTTPBody:bodyData];
}
[NSURLConnection sendAsynchronousRequest:request queue:[NSOperationQueue mainQueue] completionHandler:^(NSURLResponse *response, NSData *data, NSError *connectionError) {
datablock(data);
}];
}
在ViewController中直接调用类(+)方法:
get请求:
[HttpMethod getDataByURLString:@"http://c.3g.163.com/nc/article/headline/T1348647853363/0-140.html" WithDataBlock:^(id data) {
NSDictionary *dic = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:nil];
NSLog(@"%@", dic); //此处就可以对数据进行具体解析
}];
post请求:
[HttpMethod getDataByURLString:@"http://ipad-bjwb.bjd.com.cn/DigitalPublication/publish/Handler/APINewsList.ashx" HttpMethod:@"POST" BodyString:@"date=20131129&startRecord=1&len=30&udid=1234567890&terminalType=Iphone&cid=213" DataBlock:^(id data) {
NSDictionary *dic = [NSJSONSerialization JSONObjectWithData:data options: NSJSONReadingMutableContainers error:n