前面提到AFNetworking是一个很强大的网络三方库,首先你需要引入AFNetworking三方库;如封装的有误还请指出,谢谢!
/**Get请求
url 服务器请求地址
success 服务器响应返回的结果
faile 失败的信息
*/
+ (void)getHttpRequestURL:(NSString *)url RequestSuccess:(void(^)(id repoes,NSURLSessionDataTask *task)) success RequestFaile:(void(^)(NSError *error))faile{
AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
manager.responseSerializer = [AFHTTPResponseSerializer serializer];//放弃解析
/// [manager.requestSerializer setValue:@"application/json"forHTTPHeaderField:@"Accept"];
/// [manager.requestSerializer setValue:@"application/json;charset=utf-8"forHTTPHeaderField:@"Content-Type"];
/// [manager.requestSerializer setValue:@"http header" forHTTPHeaderField:@"XiaoGuiGe"];
[manager.requestSerializer setHTTPShouldHandleCookies:NO];
[manager GET:url parameters:nil progress:^(NSProgress * _Nonnull downloadProgress) {
} success:^(NSURLSessionDataTask * _Nonnull task, id _Nullable responseObject) {
if (success) {
//返回成功结果
success(responseObject,task);
}
} failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
//返回失败结果
faile(error);
}];
}
/**Post请求
url 服务器请求地址
pram 请求参数
success 服务器响应返回的结果
faile 失败的信息
*/
+ (void)postHttpRequestURL:(NSString *)url RequestPram:(id)pram RequestSuccess:(void(^)(id respoes))success RequestFaile:(void(^)(NSError *erro))faile{
AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
[manager POST:url parameters:pram progress:^(NSProgress * _Nonnull uploadProgress) {
///这里面是进度
} success:^(NSURLSessionDataTask * _Nonnull task, id _Nullable responseObject) {
if (success) {
//返回成功结果
success(responseObject);
}
} failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
//返回失败结果
faile(error);
}];
}
+ (void)createDownloadFileWithURLString:(NSString *)URLString downloadFileProgress:(void (^)(NSProgress *))downloadFileProgress setupFilePath:(NSURL *(^)(NSURLResponse *))setupFilePath downloadCompletionHandler:(void (^)(NSURL *, NSError *))downloadCompletionHandler{
NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL URLWithString:URLString]];
AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
manager.requestSerializer = [AFHTTPRequestSerializer serializer];
manager.responseSerializer = [AFHTTPResponseSerializer serializer];
NSURLSessionDownloadTask *dataTask = [manager downloadTaskWithRequest:request progress:^(NSProgress * _Nonnull downloadProgress) {
/**
* 下载进度
*/
downloadFileProgress(downloadProgress);
} destination:^NSURL * _Nonnull(NSURL * _Nonnull targetPath, NSURLResponse * _Nonnull response) {
/**
* 设置保存目录
*/
return setupFilePath(response);
} completionHandler:^(NSURLResponse * _Nonnull response, NSURL * _Nullable filePath, NSError * _Nullable error) {
/**
* 下载完成
*/
downloadCompletionHandler(filePath,error);
}];
[dataTask resume];
}
如有错误,还望指出!