轉(zhuǎn)自http://blog.csdn.net/codywangziham01/article/details/38088017
#import?"MJViewController.h"
#import?"AFNetworking.h"
@interfaceMJViewController?()
@end
@implementationMJViewController
/**
要使用常規(guī)的AFN網(wǎng)絡(luò)訪問
1.?AFHTTPRequestOperationManager?*manager?=?[AFHTTPRequestOperationManager?manager];
所有的網(wǎng)絡(luò)請(qǐng)求,均有manager發(fā)起
2.?需要注意的是,默認(rèn)提交請(qǐng)求的數(shù)據(jù)是二進(jìn)制的,返回格式是JSON
1>?如果提交數(shù)據(jù)是JSON的,需要將請(qǐng)求格式設(shè)置為AFJSONRequestSerializer
2>?如果返回格式不是JSON的,
3.?請(qǐng)求格式
AFHTTPRequestSerializer????????????二進(jìn)制格式
AFJSONRequestSerializer????????????JSON
AFPropertyListRequestSerializer????PList(是一種特殊的XML,解析起來相對(duì)容易)
4.?返回格式
AFHTTPResponseSerializer???????????二進(jìn)制格式
AFJSONResponseSerializer???????????JSON
AFXMLParserResponseSerializer??????XML,只能返回XMLParser,還需要自己通過代理方法解析
AFXMLDocumentResponseSerializer?(Mac?OS?X)
AFPropertyListResponseSerializer???PList
AFImageResponseSerializer??????????Image
AFCompoundResponseSerializer???????組合
*/
-?(void)viewDidLoad
{
[superviewDidLoad];
[selfreach];
}
#pragma?mark?-?演練
#pragma?mark?-?檢測(cè)網(wǎng)絡(luò)連接
-?(void)reach
{
/**
AFNetworkReachabilityStatusUnknown??????????=?-1,??//?未知
AFNetworkReachabilityStatusNotReachable?????=?0,???//?無連接
AFNetworkReachabilityStatusReachableViaWWAN?=?1,???//?3G?花錢
AFNetworkReachabilityStatusReachableViaWiFi?=?2,???//?局域網(wǎng)絡(luò),不花錢
*/
//?如果要檢測(cè)網(wǎng)絡(luò)狀態(tài)的變化,必須用檢測(cè)管理器的單例的startMonitoring
[[AFNetworkReachabilityManagersharedManager]startMonitoring];
//?檢測(cè)網(wǎng)絡(luò)連接的單例,網(wǎng)絡(luò)變化時(shí)的回調(diào)方法
[[AFNetworkReachabilityManagersharedManager]setReachabilityStatusChangeBlock:^(AFNetworkReachabilityStatus?status)?{
NSLog(@"%d",?status);
}];
}
#pragma?mark?-?Session?下載
-?(void)sessionDownload
{
NSURLSessionConfiguration*config?=?[NSURLSessionConfigurationdefaultSessionConfiguration];
AFURLSessionManager*manager?=?[[AFURLSessionManageralloc]initWithSessionConfiguration:config];
NSString*urlString?=@"http://localhost/itcast/videos/01.C語言-語法預(yù)覽.mp4";
urlString?=?[urlStringstringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
NSURL*url?=?[NSURLURLWithString:urlString];
NSURLRequest*request?=?[NSURLRequestrequestWithURL:url];
NSURLSessionDownloadTask*task?=?[managerdownloadTaskWithRequest:requestprogress:nildestination:^NSURL*(NSURL*targetPath,NSURLResponse*response)?{
//?指定下載文件保存的路徑
//????????NSLog(@"%@?%@",?targetPath,?response.suggestedFilename);
//?將下載文件保存在緩存路徑中
NSString*cacheDir?=?NSSearchPathForDirectoriesInDomains(NSCachesDirectory,?NSUserDomainMask,YES)[0];
NSString*path?=?[cacheDirstringByAppendingPathComponent:response.suggestedFilename];
//?URLWithString返回的是網(wǎng)絡(luò)的URL,如果使用本地URL,需要注意
NSURL*fileURL1=?[NSURLURLWithString:path];
NSURL*fileURL?=?[NSURLfileURLWithPath:path];
NSLog(@"==?%@?||||?%@",?fileURL1,?fileURL);
returnfileURL;
}completionHandler:^(NSURLResponse*response,NSURL*filePath,NSError*error)?{
NSLog(@"%@?%@",?filePath,?error);
}];
[taskresume];
}
#pragma?mark?-?POST?JSON
-?(void)postJSON
{
AFHTTPRequestOperationManager*manager?=?[AFHTTPRequestOperationManagermanager];
NSDictionary*dict?=?@{@"name":@"zhangsan"};
NSDictionary*dict1=?@{@"name":@"wangwu"};
NSArray*array?=?@[dict,dict1];
//?設(shè)置請(qǐng)求格式
manager.requestSerializer=?[AFJSONRequestSerializerserializer];
//?設(shè)置返回格式
manager.responseSerializer=?[AFHTTPResponseSerializerserializer];
[managerPOST:@"http://localhost/postjson.php"parameters:arraysuccess:^(AFHTTPRequestOperation*operation,idresponseObject)?{
NSString*result?=?[[NSStringalloc]initWithData:responseObjectencoding:NSUTF8StringEncoding];
NSLog(@"%@",?result);
}failure:^(AFHTTPRequestOperation*operation,NSError*error)?{
}];
}
#pragma?mark?-?隨機(jī)文件名上傳
-?(void)postUpload1
{
//?本地上傳給服務(wù)器時(shí),沒有確定的URL,不好用MD5的方式處理
AFHTTPRequestOperationManager*manager?=?[AFHTTPRequestOperationManagermanager];
manager.responseSerializer=?[AFHTTPResponseSerializerserializer];
[managerPOST:@"http://localhost/demo/upload.php"parameters:nilconstructingBodyWithBlock:^(id?formData)?{
NSURL*fileURL?=?[[NSBundlemainBundle]URLForResource:@"頭像1.png"withExtension:nil];
//?要上傳保存在服務(wù)器中的名稱
//?使用時(shí)間來作為文件名?2014-04-30?14:20:57.png
//?讓不同的用戶信息,保存在不同目錄中
NSDateFormatter*formatter?=?[[NSDateFormatteralloc]init];
//?設(shè)置日期格式
formatter.dateFormat=@"yyyy-MM-dd?HH:mm:ss";
NSString*fileName?=?[formatterstringFromDate:[NSDatedate]];
[formDataappendPartWithFileURL:fileURLname:@"uploadFile"fileName:fileNamemimeType:@"image/png"error:NULL];
}success:^(AFHTTPRequestOperation*operation,idresponseObject)?{
NSLog(@"OK");
}failure:^(AFHTTPRequestOperation*operation,NSError*error)?{
NSLog(@"error");
}];
}
#pragma?mark?-?POST上傳
-?(void)postUpload
{
AFHTTPRequestOperationManager*manager?=?[AFHTTPRequestOperationManagermanager];
//?AFHTTPResponseSerializer就是正常的HTTP請(qǐng)求響應(yīng)結(jié)果:NSData
//?當(dāng)請(qǐng)求的返回?cái)?shù)據(jù)不是JSON,XML,PList,UIImage之外,使用AFHTTPResponseSerializer
//?例如返回一個(gè)html,text...
//
//?實(shí)際上就是AFN沒有對(duì)響應(yīng)數(shù)據(jù)做任何處理的情況
manager.responseSerializer=?[AFHTTPResponseSerializerserializer];
//?formData是遵守了AFMultipartFormData的對(duì)象
[managerPOST:@"http://localhost/demo/upload.php"parameters:nilconstructingBodyWithBlock:^(id?formData)?{
//?將本地的文件上傳至服務(wù)器
NSURL*fileURL?=?[[NSBundlemainBundle]URLForResource:@"頭像1.png"withExtension:nil];
[formDataappendPartWithFileURL:fileURLname:@"uploadFile"error:NULL];
}success:^(AFHTTPRequestOperation*operation,idresponseObject)?{
NSString*result?=?[[NSStringalloc]initWithData:responseObjectencoding:NSUTF8StringEncoding];
NSLog(@"完成?%@",?result);
}failure:^(AFHTTPRequestOperation*operation,NSError*error)?{
NSLog(@"錯(cuò)誤?%@",?error.localizedDescription);
}];
}
#pragma?mark?-?JSON
-?(void)XMLData
{
AFHTTPRequestOperationManager*manager?=?[AFHTTPRequestOperationManagermanager];
//?返回的數(shù)據(jù)格式是XML
manager.responseSerializer=?[AFXMLParserResponseSerializerserializer];
NSDictionary*dict?=?@{@"format":@"xml"};
//?網(wǎng)絡(luò)訪問是異步的,回調(diào)是主線程的,因此程序員不用管在主線程更新UI的事情
[managerGET:@"http://localhost/videos.php"parameters:dictsuccess:^(AFHTTPRequestOperation*operation,idresponseObject)?{
//?如果結(jié)果是XML,同樣需要使用6個(gè)代理方法解析,或者使用第三方庫
//?第三方庫第三方框架,效率低,內(nèi)存泄漏
NSLog(@"%@",?responseObject);
}failure:^(AFHTTPRequestOperation*operation,NSError*error)?{
NSLog(@"%@",?error);
}];
}
#pragma?mark?-?JSON
-?(void)JSONData
{
AFHTTPRequestOperationManager*manager?=?[AFHTTPRequestOperationManagermanager];
//?原本需要拼接get訪問URL???&?=
NSDictionary*dict?=?@{@"format":@"json"};
//?網(wǎng)絡(luò)訪問是異步的,回調(diào)是主線程的,因此程序員不用管在主線程更新UI的事情
[managerGET:@"http://localhost/videos.php"parameters:dictsuccess:^(AFHTTPRequestOperation*operation,idresponseObject)?{
NSLog(@"%@",?responseObject);
//?提問:NSURLConnection異步方法回調(diào),是在子線程
//?得到回調(diào)之后,通常更新UI,是在主線程
NSLog(@"%@",?[NSThreadcurrentThread]);
}failure:^(AFHTTPRequestOperation*operation,NSError*error)?{
NSLog(@"%@",?error);
}];
}
#pragma?mark?-?POST登錄
-?(void)postLogin
{
AFHTTPRequestOperationManager*manager?=?[AFHTTPRequestOperationManagermanager];
//?原本需要拼接get訪問URL???&?=
NSDictionary*dict?=?@{@"username":@"wangwu",@"password":@"wang"};
//?網(wǎng)絡(luò)訪問是異步的,回調(diào)是主線程的,因此程序員不用管在主線程更新UI的事情
[managerPOST:@"http://localhost/login.php"parameters:dictsuccess:^(AFHTTPRequestOperation*operation,idresponseObject)?{
NSLog(@"%@",?responseObject);
//?提問:NSURLConnection異步方法回調(diào),是在子線程
//?得到回調(diào)之后,通常更新UI,是在主線程
NSLog(@"%@",?[NSThreadcurrentThread]);
}failure:^(AFHTTPRequestOperation*operation,NSError*error)?{
NSLog(@"%@",?error);
}];
}
#pragma?mark?-?GET登錄
-?(void)getLogin
{
AFHTTPRequestOperationManager*manager?=?[AFHTTPRequestOperationManagermanager];
//?原本需要拼接get訪問URL???&?=
NSDictionary*dict?=?@{@"username":@"wangwu",@"password":@"wang"};
//?網(wǎng)絡(luò)訪問是異步的,回調(diào)是主線程的,因此程序員不用管在主線程更新UI的事情
[managerGET:@"http://localhost/login.php"parameters:dictsuccess:^(AFHTTPRequestOperation*operation,idresponseObject)?{
NSLog(@"%@",?responseObject);
//?提問:NSURLConnection異步方法回調(diào),是在子線程
//?得到回調(diào)之后,通常更新UI,是在主線程
NSLog(@"%@",?[NSThreadcurrentThread]);
}failure:^(AFHTTPRequestOperation*operation,NSError*error)?{
NSLog(@"%@",?error);
}];
}
@end