AFNetworking的用法
AFNeiworking 用法
1、get post请求
NSString *url1 = @"http://api.openweathermap.org/data/2.5/
forecast/daily?lat=39.907501&lon=116.397232&cnt=10";//测试get请求
NSString *url2 =@"http://webservice.webxml.com.cn/
WebServices/MobileCodeWS.asmx/getMobileCodeInfo";//测试post请求
//创建一个请求管理类对象
AFHTTPRequestOperationManager* manager = [AFHTTPRequestOperationManager manager];
//注意:此行不加也可以
manager.responseSerializer.acceptableContentTypes = [manager.responseSerializer.
acceptableContentTypes setByAddingObject:@"text/html"];
//设置请求类型
manager.requestSerializer = [AFHTTPRequestSerializer serializer];
//设置返回类型 json AFXMLParserResponseSerializer:xml类型 AFHTTPResponseSerializer:二进制类型
//manager.responseSerializer = [AFJSONResponseSerializer serializer];
manager.responseSerializer = [AFXMLParserResponseSerializer serializer];
//get请求
[manager GET:url1 parameters:nil success:^(AFHTTPRequestOperation *operation,
id responseObject) {
NSLog(@"%@",responseObject);
} failure:^(AFHTTPRequestOperation *operation,NSError *error) {
NSLog(@"%@",error);
}];
//post请求,参数不显示在正文(一个网址?后面就是正文,内容就是参数),参数设置在parameters里
[manager POST:url2 parameters:@{@"mobileCode":@"15910514636",@"userID":@""}
success:^(AFHTTPRequestOperation *operation,id responseObject) {
NSLog(@"%@",responseObject);
} failure:^(AFHTTPRequestOperation *operation,NSError *error) {
NSLog(@"%@",error);
}];
2、上传
NSString* url = @"";
//参数
NSDictionary* paras =@{};
//获得的数据
NSDate* data =nil;
AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
manager.requestSerializer = [AFHTTPRequestSerializer serializer];
manager.responseSerializer = [AFJSONResponseSerializer serializer];
manager.responseSerializer.acceptableContentTypes = [manager.responseSerializer.
acceptableContentTypes setByAddingObject:@"text/html"];
AFHTTPRequestOperation *httpoperation =
[manager POST:url parameters:paras constructingBodyWithBlock:^(id<AFMultipartFormData> formData) {
//构造数据,上传的数据
[formData appendPartWithFileData:dataname:@"upload"fileName:@"image1.jpg"mimeType:nil];
} success:^(AFHTTPRequestOperation *operation,id responseObject) {
} failure:^(AFHTTPRequestOperation *operation,NSError *error) {
}];
3、监听网络状态
//开启网络状态指示器
[[AFNetworkActivityIndicatorManager sharedManager]setEnabled:YES];
//初始化监听
AFHTTPRequestOperationManager* manager = [[AFHTTPRequestOperationManager alloc]
initWithBaseURL:[NSURL URLWithString:@"http://www.baidu.com"]];
NSOperationQueue* queue = manager.operationQueue;
//监听结果回调
[manager.reachabilityManager setReachabilityStatusChangeBlock:^(AFNetworkReachabilityStatus status) {
switch (status) {
caseAFNetworkReachabilityStatusReachableViaWiFi:
caseAFNetworkReachabilityStatusReachableViaWWAN:
[queue setSuspended:NO];//设置是否挂起该进程
NSLog(@"have net");
break;
caseAFNetworkReachabilityStatusNotReachable:
default:
[queue setSuspended:YES];
NSLog(@"no");
break;
}
}];
//开始监听
[manager.reachabilityManager startMonitoring];