#pragma mark - HTTP协议
void HTTP ()
{
#pragma mark ---------- GET,JSON,XML
// 创建一个URL : 请求路径
NSString *urlStr = [NSString stringWithFormat:@"http://localhost:8080/MJServer/login?username=%@&pwd=%@",usernameText, pwdText];
NSURL *url = [NSURL URLWithString:urlStr];
// 创建一个请求
NSURLRequest *request = [NSURLRequest requestWithURL:url];
// 发送一个同步请求(在主线程发送请求)
// queue :存放completionHandler这个任务
NSOperationQueue *queue = [NSOperationQueue mainQueue];
[NSURLConnection sendAsynchronousRequest:request queue:queue completionHandler:
^(NSURLResponse *response, NSData *data, NSError *connectionError) {
// 这个block会在请求完毕的时候自动调用
if (connectionError || data == nil) {
[MBProgressHUD showError:@"请求失败"];
return;
}
// 解析服务器返回的JSON数据
NSDictionary *dict = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableLeaves error:nil];
NSString *error = dict[@"error"];
if (error) {
// {"error":"用户名不存在"}
// {"error":"密码不正确"}
[MBProgressHUD showError:error];
} else {
// {"success":"登录成功"}
NSString *success = dict[@"success"];
[MBProgressHUD showSuccess:success];
}
}];
/**
加载服务器最新的视频信息
*/
// 1.创建URL
NSURL *url = HMUrl(@"video");
// 2.创建请求
NSURLRequest *request = [NSURLRequest requestWithURL:url];
// 3.发送请求
[NSURLConnection sendAsynchronousRequest:request queue:[NSOperationQueue mainQueue] completionHandler:^(NSURLResponse *response, NSData *data, NSError *connectionError) {
if (connectionError || data == nil) {
[MBProgressHUD showError:@"网络繁忙,请稍后再试!"];
return;
}
// 解析JSON数据
NSDictionary *dict = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableLeaves error:nil];
NSArray *videoArray = dict[@"videos"];
for (NSDictionary *videoDict in videoArray) {
HMVideo *video = [HMVideo videoWithDict:videoDict];
[self.videos addObject:video];
}
// 刷新表格
[self.tableView reloadData];
}];
#pragma mark ---------- POST
// 3.发送用户名和密码给服务器(走HTTP协议)
// 创建一个URL : 请求路径
NSURL *url = [NSURL URLWithString:@"http://localhost:8080/MJServer/login"];
// 创建一个请求
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];
// 5秒后算请求超时(默认60s超时)
request.timeoutInterval = 15;
request.HTTPMethod = @"POST";
// 设置请求体
NSString *param = [NSString stringWithFormat:@"username=%@&pwd=%@", usernameText, pwdText];
// NSString --> NSData
request.HTTPBody = [param dataUsingEncoding:NSUTF8StringEncoding];
// 设置请求头信息
[request setValue:@"iPhone 6" forHTTPHeaderField:@"User-Agent"];
#pragma mark ---------- 发送JSON文件
// 1.URL
NSURL *url = [NSURL URLWithString:@"http://localhost:8080/MJServer/order"];
// 2.请求
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];
// 3.请求方法
request.HTTPMethod = @"POST";
// 4.设置请求体(请求参数)
// 创建一个描述订单信息的JSON数据
NSDictionary *orderInfo = @{
@"shop_id" : @"1243324",
@"shop_name" : @"啊哈哈哈",
@"user_id" : @"899"
};
NSData *json = [NSJSONSerialization dataWithJSONObject:orderInfo options:NSJSONWritingPrettyPrinted error:nil];
request.HTTPBody = json;
// 5.设置请求头:这次请求体的数据不再是普通的参数,而是一个JSON数据
[request setValue:@"application/json" forHTTPHeaderField:@"Content-Type"];
#pragma mark ---------- 多值参数
// 1.URL
NSURL *url = [NSURL URLWithString:@"http://localhost:8080/MJServer/weather"];
// 2.请求
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];
// 3.请求方法
request.HTTPMethod = @"POST";
// 4.设置请求体(请求参数)
NSMutableString *param = [NSMutableString string];
[param appendString:@"place=beijing"];
[param appendString:@"&place=tianjin"];
[param appendString:@"&place=meizhou"];
request.HTTPBody = [param dataUsingEncoding:NSUTF8StringEncoding];
}
#pragma mark - 数据加密
void md5 ()
{
// #import ""NSString+Hash.h
/**
* MD5($pass.$salt)
*
* @param text 明文
*
* @return 加密后的密文
*/
- (NSString *)MD5Salt:(NSString *)text
{
// 撒盐:随机地往明文中插入任意字符串
NSString *salt = [text stringByAppendingString:@"aaa"];
return [salt md5String];
}
/**
* MD5(MD5($pass))
*
* @param text 明文
*
* @return 加密后的密文
*/
- (NSString *)doubleMD5:(NSString *)text
{
return [[text md5String] md5String];
}
/**
* 先加密,后乱序
*
* @param text 明文
*
* @return 加密后的密文
*/
- (NSString *)MD5Reorder:(NSString *)text
{
NSString *pwd = [text md5String];
// 加密后pwd == 3f853778a951fd2cdf34dfd16504c5d8
NSString *prefix = [pwd substringFromIndex:2];
NSString *subfix = [pwd substringToIndex:2];
// 乱序后 result == 853778a951fd2cdf34dfd16504c5d83f
NSString *result = [prefix stringByAppendingString:subfix];
NSLog(@"\ntext=%@\npwd=%@\nresult=%@", text, pwd, result);
return result;
}
}
#pragma mark - 小文件下载
void NSData ()
{
// 下载小文件的方式
// 1.NSData dataWithContentsOfURL
// 2.NSURLConnection
// 1.NSData dataWithContentsOfURL
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
// 其实这就是一个GET请求
NSURL *url = [NSURL URLWithString:@"http://localhost:8080/MJServer/resources/images/minion_01.png"];
NSData *data = [NSData dataWithContentsOfURL:url];
NSLog(@"%d", data.length);
});
// 2.NSURLConnection
NSURL *url = [NSURL URLWithString:@"http://localhost:8080/MJServer/resources/images/minion_01.png"];
NSURLRequest *request = [NSURLRequest requestWithURL:url];
[NSURLConnection sendAsynchronousRequest:request queue:[NSOperationQueue mainQueue] completionHandler:^(NSURLResponse *response, NSData *data, NSError *connectionError) {
NSLog(@"%d", data.length);
}];
}
#pragma mark - 大文件下载
void NSURLConnection ()
{
// 1.URL
NSURL *url = [NSURL URLWithString:@"http://localhost:8080/MJServer/resources/music.zip"];
// 2.请求
NSURLRequest *request = [NSURLRequest requestWithURL:url];
// 3.下载(创建完conn对象后,会自动发起一个异步请求)
[NSURLConnection connectionWithRequest:request delegate:self];
#pragma mark - NSURLConnectionDataDelegate代理方法
/**
* 请求失败时调用(请求超时、网络异常)
*
* @param error 错误原因
*/
- (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error
{
NSLog(@"didFailWithError");
}
/**
* 1.接收到服务器的响应就会调用
*
* @param response 响应
*/
- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response
{
// 文件路径
NSString *caches = [NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES) lastObject];
NSString *filepath = [caches stringByAppendingPathComponent:@"videos.zip"];
// 创建一个空的文件 到 沙盒中
NSFileManager *mgr = [NSFileManager defaultManager];
[mgr createFileAtPath:filepath contents:nil attributes:nil];
// 创建一个用来写数据的文件句柄
self.writeHandle = [NSFileHandle fileHandleForWritingAtPath:filepath];
// 获得文件的总大小
self.totalLength = response.expectedContentLength;
}
/**
* 2.当接收到服务器返回的实体数据时调用(具体内容,这个方法可能会被调用多次)
*
* @param data 这次返回的数据
*/
- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data
{
// 移动到文件的最后面
[self.writeHandle seekToEndOfFile];
// 将数据写入沙盒
[self.writeHandle writeData:data];
// 累计文件的长度
self.currentLength += data.length;
NSLog(@"下载进度:%f", (double)self.currentLength/ self.totalLength);
self.circleView.progress = (double)self.currentLength/ self.totalLength;
}
/**
* 3.加载完毕后调用(服务器的数据已经完全返回后)
*/
- (void)connectionDidFinishLoading:(NSURLConnection *)connection
{
self.currentLength = 0;
self.totalLength = 0;
// 关闭文件
[self.writeHandle closeFile];
self.writeHandle = nil;
}
#pragma mark ---------- 断点下载
/**
* 1.接收到服务器的响应就会调用
*
* @param response 响应
*/
- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response
{
if (self.currentLength) return;
// 文件路径
NSString *caches = [NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES) lastObject];
NSString *filepath = [caches stringByAppendingPathComponent:@"videos.zip"];
// 创建一个空的文件 到 沙盒中
NSFileManager *mgr = [NSFileManager defaultManager];
[mgr createFileAtPath:filepath contents:nil attributes:nil];
// 创建一个用来写数据的文件句柄
self.writeHandle = [NSFileHandle fileHandleForWritingAtPath:filepath];
// 获得文件的总大小
self.totalLength = response.expectedContentLength;
}
/**
* 2.当接收到服务器返回的实体数据时调用(具体内容,这个方法可能会被调用多次)
*
* @param data 这次返回的数据
*/
- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data
{
// 移动到文件的最后面
[self.writeHandle seekToEndOfFile];
// 将数据写入沙盒
[self.writeHandle writeData:data];
// 累计文件的长度
self.currentLength += data.length;
self.circleView.progress = (double)self.currentLength/ self.totalLength;
}
/**
* 3.加载完毕后调用(服务器的数据已经完全返回后)
*/
- (void)connectionDidFinishLoading:(NSURLConnection *)connection
{
self.currentLength = 0;
self.totalLength = 0;
// 关闭文件
[self.writeHandle closeFile];
self.writeHandle = nil;
}
- (IBAction)download:(UIButton *)sender {
// 状态取反
sender.selected = !sender.isSelected;
// 断点续传
// 断点下载
if (sender.selected) { // 继续(开始)下载
// 1.URL
NSURL *url = [NSURL URLWithString:@"http://localhost:8080/MJServer/resources/videos.zip"];
// 2.请求
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];
// 设置请求头bytes=%@-
NSString *range = [NSString stringWithFormat:@"bytes=%lld-", self.currentLength];
[request setValue:range forHTTPHeaderField:@"Range"];
// 3.下载(创建完conn对象后,会自动发起一个异步请求)
self.conn = [NSURLConnection connectionWithRequest:request delegate:self];
} else { // 暂停
[self.conn cancel];
self.conn = nil;
}
}
}
#pragma mark - NSURLConnection GET数据请求
@interface XLRootViewController ()<UITableViewDataSource,UITableViewDelegate,NSURLConnectionDataDelegate>
{
NSMutableArray * dataSource;
UITableView * table;
//定义一个可变data对象:一个任务分给多个线程完成 每个线程完成的都不是完整任务 需要将每个线程完成的部分拼接到一起才是一个完整的任务
//服务器上请求下来的数据类型NSData
NSMutableData * myData;
}
@end
-(void)pressBar:(id)sender
{
//<1>将字符串转化成NSURL
NSURL * url = [NSURL URLWithString:@"http://10.0.8.8/sns/my/user_list/php?page=2&number=1000"];
//<2>将NSURL封装成请求对象
// NSData * data = [NSData dataWithContentsOfURL:url];
// NSDictionary * dic = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:nil];
//【注意】将接口下的数据直接转化NSData 这种方式称其为同步请求
NSURLRequest * request = [NSURLRequest requestWithURL:url];
//<3>开始异步请求
//系统类NSURLConnection 进行异步请求 只能进行单任务异步请求
//就是单个任务交给多个线程 同时工作 互不干扰 直到完成同一个任务
[NSURLConnection connectionWithRequest:request delegate:self];
}
// NSURLConnectionDataDelegate
//以下三个方法是必须实现的方法
//<1>
-(void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response
{
NSLog(@"服务器端接收客户端的响应");
//-----------------扩展-------------------
//获取响应状态
//NSURLResponse是所有响应类的父类 设备和设备之间相互通信要遵守HTTP协议 所以此处的响应对象的类型NSHTTPURLResponse类型
NSHTTPURLResponse * httpResponse = (NSHTTPURLResponse *)response;
NSInteger status = [httpResponse statusCode];
NSLog(@"%ld",status);
/*
200 请求数据成功
404 请求的数据不存在
400 请求数据的客户端出现语法错误
500 请求数据服务器端出现语法错误
*/
//----------------------------------------
//下面的代码必须写
//myData在使用之前必须清空 以免对后面的结果产生影响
if(myData == nil)
{
myData = [[NSMutableData alloc]init];
}
else
{
myData.length = 0;
}
}
//<2>
-(void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data
{
NSLog(@"开始接收数据");
//每个线程请求数据结束 都会调用该方法 直到所有线程请求数据结束
[myData appendData:data];
}
//<3>
-(void)connectionDidFinishLoading:(NSURLConnection *)connection
{
//代码运行到该方法 就证明数据请求结束
//开始数据解析
NSDictionary * dic = [NSJSONSerialization JSONObjectWithData:myData options:NSJSONReadingMutableContainers error:nil];
NSArray * array = dic[@"users"];
[dataSource addObjectsFromArray:array];
//数据源发生改变 刷新表格
[table reloadData];
}
#pragma mark - NSURLConnection进行POST请求 账号注册
//代理
@interface XLViewController ()<NSURLConnectionDataDelegate>
{
NSMutableData * myData;
}
@end
- (IBAction)registerBtn:(id)sender
{
//NSURLConnectionPOST单任务请求
//<1>将请求数据的字符串接口转化成NSURL
NSURL * url = [NSURL URLWithString:PATH];
//<2>封装成请求对象
//GET 请求封装的请求对象是NSURLRequest
//POST 请求封装的请求对象是NSMutableURLRequest
NSMutableURLRequest * request = [NSMutableURLRequest requestWithURL:url];
//<3>设置请求方式
//GET 请求不需要设置
[request setHTTPMethod:@"POST"];
//<4>设置请求样式
//请求体的格式是参数名=参数值&参数名=参数值....
[request setValue:@"application/x-www-form-urlencoded" forHTTPHeaderField:@"Content-Type"];
//<5>拼接请求体
NSString * bodyStr = [NSString stringWithFormat:@"username=%@&password=%@&email=%@",self.nameTextField.text,self.passWordTextField.text,self.emailTextField.text];
//<6>设置请求体的长度
//【注意】设置请求体的长度就是设置请求体转化成NSData类型的长度
NSData * bodyData = [bodyStr dataUsingEncoding:NSUTF8StringEncoding];
[request setValue:[NSString stringWithFormat:@"%d",(int)bodyData.length] forHTTPHeaderField:@"Content-Length"];
//<7>设置请求体
[request setHTTPBody:bodyData];
//<8>开始请求数据
[NSURLConnection connectionWithRequest:request delegate:self];
}
-(void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response
{
if(myData == nil)
{
myData = [[NSMutableData alloc]init];
}
else
{
myData.length = 0;
}
}
-(void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data
{
[myData appendData:data];
}
-(void)connectionDidFinishLoading:(NSURLConnection *)connection
{
//json解析
NSDictionary * dic = [NSJSONSerialization JSONObjectWithData:myData options:NSJSONReadingMutableContainers error:nil];
NSString * message = dic[@"message"];
NSLog(@"%@",message);
}
#pragma mark - NSURLSession进行GET请求
-(void)requestInfo
{
dataSource = [[NSMutableArray alloc]init];
//NSURLSession是NSURLConnection重构以后出现的类
//在前台两种类的工作原理完全相同 也具有相同的类比如说NSURLRequest、NSURLCache等 不同的地方就是NSURLSession可以在后台执行 除非用户强行将后台关闭才能停止NSURL Session的工作 也就是NSURLSession在后台开了工作线程,NSURLSession支持上传也支持下载
//<1>将字符串网址转化成NSURL
NSURL * url = [NSURL URLWithString:PATH];
//<2>封装成请求对象
NSURLRequest * request = [NSURLRequest requestWithURL:url];
//<3>创建NSURLSession的对象
NSURLSession * session = [NSURLSession sharedSession];
//<4>开始请求数据
NSURLSessionDataTask * task = [session dataTaskWithRequest:request completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) {
NSDictionary * dic = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:nil];
NSArray * array = dic[@"list"];
[dataSource addObjectsFromArray:array];
//------------------重点------------
//⚠ 如果需要刷新表格操作 必须借助GCD中修改主线程的方法
dispatch_async(dispatch_get_main_queue(), ^{
[table reloadData];
});
}];
//<5>开始请求
[task resume];
}
#pragma mark - NSURLSession进行POST请求
-(void)pressBtn:(id)sender
{
//NSURLSession 进行POST请求
//<1>将字符串网址转化成NSURL
NSURL * url = [NSURL URLWithString:PATH];
//<2>封装成请求对象
NSMutableURLRequest * request = [NSMutableURLRequest requestWithURL:url];
//<3>设置请求方法
[request setHTTPMethod:@"POST"];
//<4>拼接请求体
UITextField * field = (UITextField *)[self.view viewWithTag:100];
NSString * bodyStr = [NSString stringWithFormat:@"chgmobile=%@",field.text];
NSData * bodyData = [bodyStr dataUsingEncoding:NSUTF8StringEncoding];
[request setHTTPBody:bodyData];
//<5>创建NSURLSession对象
NSURLSession * session = [NSURLSession sharedSession];
//<6>进行数据请求
NSURLSessionDataTask * task = [session dataTaskWithRequest:request completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) {
GDataXMLDocument * document = [[GDataXMLDocument alloc]initWithData:data options:0 error:nil];
NSArray * province = [document nodesForXPath:@"//province" error:nil];
NSArray * city = [document nodesForXPath:@"//city" error:nil];
NSArray * supplier = [document nodesForXPath:@"//supplier" error:nil];
NSLog(@"%@--%@--%@",[province[0] stringValue],[city[0] stringValue],[supplier[0] stringValue]);
}];
//<7>
[task resume];
}
#pragma mark - NSURLSession进行断点续传下载
#import "ViewController.h"
#import "AFHTTPRequestOperationManager.h"
#define PATH @"http://yl.cms.palmtrends.com/upload/1445911639/201510271010032_listthumb_iphone4.png"
//NSURLSession里面用三个任务 NSURLSessionDataTask 、NSURLSessionDownloadTask、NSURLSessionUploadTask
@interface ViewController ()<NSURLSessionDownloadDelegate>
{
//定义NSURLSession对象
NSURLSession * session;
//创建下载任务对象
NSURLSessionDownloadTask * task;
//创建请求对象
NSURLRequest * request;
//定义一个NSData类型的变量 接收下载下来的数据
NSData * data;
}
@end
@implementation ViewController
-(void)checkedNet
{
//<1>创建请求操作管理者对象
AFHTTPRequestOperationManager * manager = [AFHTTPRequestOperationManager manager];
//<2>判断网络状态
[manager.reachabilityManager setReachabilityStatusChangeBlock:^(AFNetworkReachabilityStatus status) {
if(status == AFNetworkReachabilityStatusReachableViaWiFi)
{
NSLog(@"WIFI");
}
else if (status == AFNetworkReachabilityStatusReachableViaWWAN)
{
NSLog(@"3G/4G/GPRS");
}
else if (status == AFNetworkReachabilityStatusNotReachable)
{
NSLog(@"无网络连接");
}
else
{
NSLog(@"网络未知");
}
}];
//<3>开启网络测试
[manager.reachabilityManager startMonitoring];
}
- (void)viewDidLoad {
[super viewDidLoad];
//判断当前的网络状态
[self checkedNet];
}
- (void)didReceiveMemoryWarning {
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
- (IBAction)startBtn:(id)sender
{
//<1>创建NSURLSession的配置信息对象
NSURLSessionConfiguration * configuration = [NSURLSessionConfiguration defaultSessionConfiguration];
//<2>创建session对象 将配置信息与session对象进行关联
session = [NSURLSession sessionWithConfiguration:configuration delegate:self delegateQueue:nil];
//<3>将路径转化成NSURL
NSURL * url = [NSURL URLWithString:PATH];
//<4>创建请求对象
request = [NSURLRequest requestWithURL:url];
//<5>进行数据请求
task = [session downloadTaskWithRequest:request];
//<6>开始请求
NSLog(@"开始下载");
[task resume];
}
- (IBAction)pauseBtn:(id)sender
{
//暂停
NSLog(@"暂停");
[task cancelByProducingResumeData:^(NSData *resumeData) {
//resumeData中存放的就是下载下来的数据
data = resumeData;
}];
}
- (IBAction)recoverBtn:(id)sender
{
NSLog(@"恢复");
if(!data)
{
NSURL * url = [NSURL URLWithString:PATH];
request = [NSURLRequest requestWithURL:url];
task = [session downloadTaskWithRequest:request];
}
else
{
//继续下载
task = [session downloadTaskWithResumeData:data];
}
[task resume];
}
//NSURLSessionDownLoadDelegate 代理方法
//下载结束
-(void)URLSession:(NSURLSession *)session downloadTask:(NSURLSessionDownloadTask *)downloadTask didFinishDownloadingToURL:(NSURL *)location
{
//<1>获取存放信息的路径
NSURL * url = [NSURL fileURLWithPath:@"/Users/xuli/Desktop/image.png"];
//<2>通过文件管理对象将下载下来的文件路径移到url路径下
NSFileManager * manager = [NSFileManager defaultManager];
[manager moveItemAtURL:location toURL:url error:nil];
//<3>修改主线程
dispatch_async(dispatch_get_main_queue(), ^{
//将文件下的内容读取出来添加到图片视图上
NSData * imageData = [manager contentsAtPath:@"/Users/xuli/Desktop/image.png"];
UIImage * image = [UIImage imageWithData:imageData];
self.iconImageView.image = image;
});
}
//获取下载进度
-(void)URLSession:(NSURLSession *)session downloadTask:(NSURLSessionDownloadTask *)downloadTask didWriteData:(int64_t)bytesWritten totalBytesWritten:(int64_t)totalBytesWritten totalBytesExpectedToWrite:(int64_t)totalBytesExpectedToWrite
{
//totalBytesWritten此时下载的二进制数据大小
//totalBytesExpectedToWrite 预期下载量
CGFloat progress = (totalBytesWritten * 1.0)/totalBytesExpectedToWrite;
//修改主线程进度条
dispatch_async(dispatch_get_main_queue(), ^{
self.myProgress.progress = progress;
});
}
@end
#pragma mark - AFNetWorking GET请求以及GData的使用
#import "AFHTTPRequestOperationManager.h"
#import "GDataXMLNode.h"
-(void)pressBtn:(id)sender
{
UIButton * btn = (UIButton *)sender;
if(btn.tag == 1)
{
//请求jSON数据
//<1>创建请求操作管理者对象
AFHTTPRequestOperationManager * manager = [AFHTTPRequestOperationManager manager];
//<2>设置请求的数据类型(json、xml)
manager.responseSerializer.acceptableContentTypes = [NSSet setWithObject:@"application/json"];
//<3>开始请求数据并解析
[manager GET:kJSONUrlString parameters:nil success:^(AFHTTPRequestOperation *operation, id responseObject) {
//此时responseObject就是解析以后的数据 如果json数据根是字典那么responseObject就是字典 如果是数组那么responseObject就是数组
NSLog(@"%@",responseObject);
} failure:^(AFHTTPRequestOperation *operation, NSError *error) {
NSLog(@"%@",error.description);
}];
}
else
{
//xml数据请求
//<1>创建请求操作管理者对象
AFHTTPRequestOperationManager * manager = [AFHTTPRequestOperationManager manager];
//<2>设置请求数据的类型(json、xml)
manager.responseSerializer.acceptableContentTypes = [NSSet setWithObject:@"text/xml"];
//<3>AFNetworking 提供的xml数据解析非常复杂 一般的时候都是用第三方库GData 所以关闭AFN提供的xml解析
manager.responseSerializer = [AFHTTPResponseSerializer serializer];
//<4>开始请求数据
[manager GET:kXMLUrlString parameters:nil success:^(AFHTTPRequestOperation *operation, id responseObject) {
//<1>将所有数据解析出来放在内存中
GDataXMLDocument * document = [[GDataXMLDocument alloc]initWithData:responseObject options:0 error:nil];
//<2>根据路径查找想要的节点信息
NSArray * array = [document nodesForXPath:@"//title" error:nil];
//<3>遍历数组中的节点内容
for(GDataXMLElement * element in array)
{
//获取节点的内容调用的方法是stringValue
NSLog(@"%@",element.stringValue);
}
} failure:^(AFHTTPRequestOperation *operation, NSError *error) {
NSLog(@"%@",error.description);
}];
}
}
#pragma mark -AFNetworking能进行多任务异步请求,是GET请求
#import "XLViewController.h"
#import "AFHTTPRequestOperationManager.h"
@interface XLViewController ()
@end
@implementation XLViewController
-(void)createUI
{
for(int i = 0;i<3;i++)
{
UIImageView * imageView = [[UIImageView alloc]initWithFrame:CGRectMake(0, 150 * i, self.view.frame.size.width,150)];
imageView.tag = i + 1;
[self.view addSubview:imageView];
}
}
- (void)viewDidLoad
{
[super viewDidLoad];
[self createUI];
//AFNetworking能进行多任务异步请求,是GET请求
NSArray * imageArr = @[@"http://mp.manzuo.com/pic/act/banner_20150416144658_20150514104127.jpg",
@"http://10.0.8.8/sns/attachment/201412/20/93916_1419040676yd6Q.jpg",
@"http://mp.manzuo.com/pic/act/banner_20150520104032.jpg"];
//【注意】一个请求对象只能请求一个接口的数据
//定义一个可变数组存放三个请求对象 然后将请求对象放在队列中
NSMutableArray * requestArr = [[NSMutableArray alloc]init];
for(int i = 0;i<3;i++)
{
//<1>将字符串接口转化成NSURL
NSURL * url = [NSURL URLWithString:imageArr[i]];
//<2>将NSURL封装成请求对象
NSURLRequest * request = [NSURLRequest requestWithURL:url];
//<3>将请求对象封装成请求操作对象
AFHTTPRequestOperation * operation = [[AFHTTPRequestOperation alloc]initWithRequest:request];
//<4>对象请求数据结束以后将内容显示在UIImageView上
[operation setCompletionBlockWithSuccess:^(AFHTTPRequestOperation *operation, id responseObject)
{
//将responseObject NSData类型的数据转化成UIImage
UIImage * image = [UIImage imageWithData:responseObject];
UIImageView * imageView = (UIImageView *)[self.view viewWithTag:i + 1];
imageView.image = image;
NSLog(@"request%d",i + 1);
} failure:^(AFHTTPRequestOperation *operation, NSError *error) {
NSLog(@"%@",error.description);
}];
//<5>将请求对象放在数组中
[requestArr addObject:operation];
}
//<6>创建队列对象
NSOperationQueue * queue = [[NSOperationQueue alloc]init];
//<7>设置最大请求数据的对象个数
queue.maxConcurrentOperationCount = 3;
//<8>将所有请求对象放在队列中
[queue addOperations:requestArr waitUntilFinished:NO];
}
#pragma mark -AFNetWorking进行POST请求 登陆和上传
//登陆
//<1>创建请求操作管理者对象
AFHTTPRequestOperationManager * manager = [AFHTTPRequestOperationManager manager];
//<2>设置接收的数据类型(json、xml)
manager.responseSerializer.acceptableContentTypes = [NSSet setWithObject:@"text/html"];
//<3>拼接请求体
//AFNetWorking中请求体是使用字典存放的
//字典的键是参数名称 字典的值就是参数值(从键盘输入的内容)
NSDictionary * dic = @{@"username":self.nameTextField.text,@"password":self.pswTextField.text};
//<4>请求数据并解析
[manager POST:LOGINPATH parameters:dic success:^(AFHTTPRequestOperation *operation, id responseObject)
{
//数据就是一个字典
NSString * code = responseObject[@"code"];
NSString * message = responseObject[@"message"];
//---------关键-------------
NSString * token = responseObject[@"m_auth"];
album.albumToken = token;
//token用户授权的标示
} failure:^(AFHTTPRequestOperation *operation, NSError *error) {
NSLog(@"%@",error.description);
}];
//上传图片 要在获取图拍的方法里面
//UIImagePickerControllerDelegate方法
-(void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info
{
//<1>获取图片信息
UIImage * image = [info objectForKey:UIImagePickerControllerOriginalImage];
//<2>图片的上传要上传二进制格式
NSData * imageData = UIImagePNGRepresentation(image);
//<3>开始数据请求
NSDictionary * dic = @{@"m_auth":self.albumToken,@"albumid":@(0),@"pic_title":@"image.png"};
AFHTTPRequestOperationManager * manager = [AFHTTPRequestOperationManager manager];
manager.responseSerializer.acceptableContentTypes = [NSSet setWithObject:@"text/html"];
//上传二进制数据
[manager POST:UPLOADPATH parameters:dic constructingBodyWithBlock:^(id<AFMultipartFormData> formData) {
//将图片的二进制与接口进行拼接
/*
1、上传的图片的二进制格式
2、上传的二进制对应的参数名称
3、上传的文件的名称(名称任意 但不能带有中文 最好添加后缀)
4、格式是固定的 (image/png)
*/
[formData appendPartWithFileData:imageData name:@"attach" fileName:@"hello.png" mimeType:@"image/png"];
} success:^(AFHTTPRequestOperation *operation, id responseObject) {
//数据请求并解析成功
NSLog(@"%@",responseObject[@"message"]);
} failure:^(AFHTTPRequestOperation *operation, NSError *error) {
NSLog(@"%@",error.description);
}];
[picker dismissViewControllerAnimated:YES completion:nil];
}
#pragma mark -AFNetWorking进行网络状态检查
-(void)checkedNet
{
//<1>创建请求操作管理者对象
AFHTTPRequestOperationManager * manager = [AFHTTPRequestOperationManager manager];
//<2>判断网络状态
[manager.reachabilityManager setReachabilityStatusChangeBlock:^(AFNetworkReachabilityStatus status) {
if(status == AFNetworkReachabilityStatusReachableViaWiFi)
{
NSLog(@"WIFI");
}
else if (status == AFNetworkReachabilityStatusReachableViaWWAN)
{
NSLog(@"3G/4G/GPRS");
}
else if (status == AFNetworkReachabilityStatusNotReachable)
{
NSLog(@"无网络连接");
}
else
{
NSLog(@"网络未知");
}
}];
//<3>开启网络测试
[manager.reachabilityManager startMonitoring];
}
#pragma mark - SDWebImage第三方库的使用
//头文件
#import "UIImageView+WebCache.h"//为图片视图异步加载图片
//获取图片的接口
NSString * path = dataSource[indexPath.row][@"icon"];
NSString * imagePath = [NSString stringWithFormat:@"http://yl.cms.palmtrends.com%@",path];
//同步请求数据
// NSURL * url = [NSURL URLWithString:imagePath];
// NSData * data = [NSData dataWithContentsOfURL:url];
// UIImage * image = [UIImage imageWithData:data];
// cell.iconImageView.image = image;
//异步请求数据
NSURL * url = [NSURL URLWithString:imagePath];
[cell.iconImageView setImageWithURL:url];
//setImageWithUrl是SDWebImage第三方库中的方法