#import "ViewController.h"#import "HttpResquestHelper.h"@interface ViewController ()- (IBAction)get:(id)sender;
- (IBAction)post:(id)sender;
- (IBAction)block:(id)sender;
- (IBAction)delete:(id)sender;
@property(nonatomic,strong)NSMutableData *data;
@end
@implementation ViewController
- (void)viewDidLoad {
[super viewDidLoad];
// Do any additional setup after loading the view, typically from a nib.
}
- (void)didReceiveMemoryWarning {
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
#pragma mark -----nsurlsection注意:所有的请求都必须要用resume开启
//get请求
- (IBAction)get:(id)sender {
//1.封装网址对象
NSString *urlstring =@"http://ipad-bjwb.bjd.com.cn/DigitalPublication/publish/Handler/APINewsList.ashx?date=20131129&startRecord=1&len=5&udid=1234567890&terminalType=Iphone&cid=213";
NSURL *url =[NSURL URLWithString:urlstring];
//2.设置网络请求
NSMutableURLRequest *request =[NSMutableURLRequest requestWithURL:url];
//创建一个session对象,他是单利方法
NSURLSession *session=[NSURLSession sharedSession];
//3.创建有个请求任务
NSURLSessionDataTask *task =[session dataTaskWithRequest:request completionHandler:^(NSData * _Nullable data, NSURLResponse * _Nullable response, NSError * _Nullable error) {
NSString *result =[[NSString alloc]initWithData:data encoding:NSUTF8StringEncoding];
NSLog(@"%@",result);
}];
[task resume];
}
- (IBAction)post:(id)sender {
//1.封装网址
NSString *urlstring =@"http://ipad-bjwb.bjd.com.cn/DigitalPublication/publish/Handler/APINewsList.ashx";
NSURL *url =[NSURL URLWithString:urlstring];
//2.设置post请求
NSMutableURLRequest *request =[NSMutableURLRequest requestWithURL:url];
[request setHTTPMethod:@"POST"];
NSString *poststring =@"?date=20131129&startRecord=1&len=5&udid=1234567890&terminalType=Iphone&cid=213";
NSData *postdata =[poststring dataUsingEncoding:NSUTF8StringEncoding];
[request setHTTPBody:postdata];
// NSData *data =[NSURLConnection sendSynchronousRequest:request returningResponse:nil error:nil];
// NSString *result =[[NSString alloc]initWithData:data encoding:NSUTF8StringEncoding];
// NSLog(@"%@",result);
//3.创建请求任务
//创建一个session单利
NSURLSession *session =[NSURLSession sharedSession];
NSURLSessionDataTask *task =[session dataTaskWithRequest:request completionHandler:^(NSData * _Nullable data, NSURLResponse * _Nullable response, NSError * _Nullable error) {
NSString *result =[[NSString alloc]initWithData:data encoding:NSUTF8StringEncoding];
NSLog(@"%@",result);
}];
[task resume];
}
#pragma mark ------block
- (IBAction)block:(id)sender {
HttpResquestHelper *request =[HttpResquestHelper defaultmanager];
[request requestWithMrthod:@"GET" url:@"http://ipad-bjwb.bjd.com.cn/DigitalPublication/publish/Handler/APINewsList.ashx?date=20131129&startRecord=1&len=5&udid=1234567890&terminalType=Iphone&cid=213" parameter:@"" complitewithdata:^(NSData *data){
NSLog(@"%@",[[NSString alloc]initWithData:data encoding:NSUTF8StringEncoding]);
}];
}
#pragma mark ----nsurlsessiondatatask--
//接受服务器响应
-(void)URLSession:(NSURLSession *)session dataTask:(NSURLSessionDataTask *)dataTask didReceiveResponse:(NSURLResponse *)response completionHandler:(void (^)(NSURLSessionResponseDisposition))completionHandler{
//当网络是基于HTTP协议时response是nshttpurlresponse类型的
NSHTTPURLResponse *httpresponse =(NSHTTPURLResponse *)response;
long long length = httpresponse.expectedContentLength;
NSLog(@"%lld",length);
// NSLog(@"statusCode:%ld",httpresponse.statusCode);
// NSLog(@"%@",response);
completionHandler(NSURLSessionResponseAllow);
self.data =[NSMutableData data];
}
//接收数据{
-(void)URLSession:(NSURLSession *)session dataTask:(NSURLSessionDataTask *)dataTask didReceiveData:(NSData *)data{
[self.data appendData:data];
NSString *string =[[NSString alloc]initWithData:self.data encoding:NSUTF8StringEncoding];
NSLog(@"%@",string);
}
//完成时或者请求失败
-(void)URLSession:(NSURLSession *)session task:(NSURLSessionTask *)task didCompleteWithError:(NSError *)error{
NSLog(@"123");
}
//设置代理请求
- (IBAction)delete:(id)sender {
NSString *urlstring =@"http://ipad-bjwb.bjd.com.cn/DigitalPublication/publish/Handler/APINewsList.ashx?date=20131129&startRecord=1&len=5&udid=1234567890&terminalType=Iphone&cid=213";
NSURL *url =[NSURL URLWithString:urlstring];
//使用代理方法我们需设置代理,但是session的delete是只读,想要设置得通过如下方法
NSURLSession *session =[NSURLSession sessionWithConfiguration:[NSURLSessionConfiguration defaultSessionConfiguration] delegate:self delegateQueue:[NSOperationQueue mainQueue]];
//创建任务.因为我们
NSMutableURLRequest *request =[NSMutableURLRequest requestWithURL:url];
NSURLSessionDataTask *task =[session dataTaskWithRequest:request];
//NSString *result =[[NSString alloc]initWithData:data encoding:NSUTF8StringEncoding];
//NSLog(@"%@",result);
[task resume];
NSLog(@"fffffffff");
}
封装用的模型
#import "HttpResquestHelper.h"
static HttpResquestHelper *helper =nil;
@implementation HttpResquestHelper
+(instancetype)defaultmanager{
static dispatch_once_t onceToken;
dispatch_once(&onceToken,^{
helper =[[HttpResquestHelper alloc]init];
});
return helper;
}
- (void)requestWithMrthod:(NSString *)method url:(NSString *)urlstring parameter:(NSString *)parameter complitewithdata:(BLOCK)block {
NSURL *url =[NSURL URLWithString:urlstring];
NSMutableURLRequest *request =[NSMutableURLRequest requestWithURL:url cachePolicy:NSURLRequestUseProtocolCachePolicy timeoutInterval:0];
if ([method isEqualToString:@"POST"]) {
request.HTTPMethod =@"POST";
request.HTTPBody =[parameter dataUsingEncoding:NSUTF8StringEncoding];
}
//创建请求任务,
NSURLSession *session =[NSURLSession sharedSession];
NSURLSessionDataTask *task =[session dataTaskWithRequest:request completionHandler:^(NSData * _Nullable data, NSURLResponse * _Nullable response, NSError * _Nullable error) {
block(data);
}];
[task resume];
}
@end