1.NSURLConnection
NSString *urlString = @"http:// + (請求字段)";
//url
NSURL *url = [NSURL URLWithString:urlString] ;
//request
NSURLRequest *request = [NSURLRequest requestWithURL:url] ;
//發(fā)送請求
[NSURLConnection sendAsynchronousRequest:request queue:queue completionHandler:^(NSURLResponse * _Nullable response, NSData * _Nullable data, NSError * _Nullable connectionError) {
//解析data
}] ;
*post*與*get*不同的是:*post*需要設置請求方式和請求體
request.HTTPMethod = @"POST" ;
request.HTTPBody = [@"cid_rel=207&page=1" dataUsingEncoding:NSUTF8StringEncoding] ;
[NSURLConnection sendAsynchronousRequest:request queue:queue completionHandler:^(NSURLResponse * _Nullable response, NSData * _Nullable data, NSError * _Nullable connectionError) {
//解析data
}] ;
NSData *resultData = [NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&error] ;
- 1.4代理請求的方式:
- 1.遵守
NSURLConnectionDataDelegate
協(xié)議才漆。
- 2.實現(xiàn)
代理方法
//該方法當接收到返回數(shù)據(jù)時會被調用 , 在其中進行了數(shù)據(jù)容器的初始化操作:
- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response {
NSLog(@"接收響應") ;
}
//該方法在接收數(shù)據(jù)過程中被多次調用 , 在其中會將接收到的數(shù)據(jù)傳遞進來:
- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data {
NSLog(@"接收數(shù)據(jù)") ;
//NSMutableData *myData
[self.myData appendData:data] ;
}
//該方法在接收數(shù)據(jù)完成之后調用 , 在其中將接受到完整的數(shù)據(jù)轉化為字符串進行了打印操作:
- (void)connectionDidFinishLoading:(NSURLConnection *)connection {
NSLog(@"數(shù)據(jù)接收完畢") ;
NSDictionary *dic = [NSJSONSerialization JSONObjectWithData:self.myData options:NSJSONReadingMutableContainers error:nil] ;
NSLog(@"%@",dic) ;
}
2.NSURLSession
//session管理者
//share-->單例:
NSURLSession *session = [NSURLSession sharedSession] ;
//請求網(wǎng)絡數(shù)據(jù)
NSURLSessionDataTask *task = [session dataTaskWithRequest:request completionHandler:^(NSData * _Nullable data, NSURLResponse * _Nullable response, NSError * _Nullable error) {
//解析data
}];
//發(fā)起網(wǎng)絡請求
[task resume] ;
request.HTTPMethod = @"POST" ;
request.HTTPBody = [@"cid_rel=200&page=4" dataUsingEncoding:NSUTF8StringEncoding] ;
NSURLSession *session = [NSURLSession sharedSession] ;
NSURLSessionDataTask *task = [session dataTaskWithRequest:request completionHandler:^(NSData * _Nullable data, NSURLResponse * _Nullable response, NSError * _Nullable error) {
//解析數(shù)據(jù)data ;
//打印error ;
}] ;
//發(fā)起網(wǎng)絡請求
[task resume] ;
愿編程讓這個世界更美好