自己写的网络数据请求 第三方框架 断点续传 上传下载
2015-05-22 09:57
429 查看
一:需要用到第三方框架AFNetworking,直接写在工程pch头文件里就行因为经常用到它,这在网上随便下载就行,最好用cocopod来下载,这样什么都有了,cocopod是什么,我就不说,博客上面有介绍。
开始啦:
1:自定义网络请求DataRequestManager类专门管理网络用的
朋友们以下代码就可以直接复制来用了
.h文件
// DataRequestManager.h
// TestKeyBoard
// Created by mac on 14-10-21.
// Copyright (c) 2014年 mac. All rights reserved.
#import <Foundation/Foundation.h>
@protocol DataRequestManagerDelegate<NSObject>
//通过代理传值到需要的地方
- (void)passValue:(id)value;
@optional
- (void)passGetValue:(id)getValue;
@end
@interface DataRequestManager :
NSObject
{
AFHTTPRequestOperationManager *manager;//创建请求(iOS 6-7)
AFURLSessionManager *sessionManager;
//创建请求(iOS7专用)
AFHTTPRequestOperation *operation;
//创建请求管理(用于上传和下载)
}
@property (nonatomic,assign)
id<DataRequestManagerDelegate> delegate;
//GET请求调用方法
- (void)methodGetWithURL:(NSString *)urlString;
//POST请求调用方法
- (void)methodPostWithURL:(NSString *)urlString parameters:(NSDictionary *)parameters;
//上传图片
- (void)methodUploadWithURL:(NSString *)urlString parameters:(NSDictionary *)parameters image:(UIImage *)image;
@end
.m文件
// DataRequestManager.m
// TestKeyBoard
//
// Created by mac on 14-10-21.
// Copyright (c) 2014年 mac. All rights reserved.
//
#import "DataRequestManager.h"
#import "AFNetworking.h"
@implementation DataRequestManager
//GET请求
- (void)methodGetWithURL:(NSString *)urlString
{
//致空请求
if (manager) {
manager =
nil;
}
//创建请求
manager = [AFHTTPRequestOperationManagermanager];
//设置请求的解析器为AFHTTPResponseSerializer(用于直接解析数据NSData),默认为AFJSONResponseSerializer(用于解析JSON)
// manager.responseSerializer = [AFHTTPResponseSerializer serializer];
//发送GET请求
[manager GET:urlStringparameters:nilsuccess:^(AFHTTPRequestOperation
*operation,id responseObject) {
//请求成功(当解析器为AFJSONResponseSerializer时)
NSLog(@"getSuccess: %@", responseObject);
[self.delegatepassGetValue:responseObject];
//请求成功(当解析器为AFHTTPResponseSerializer时)
// NSString *JSONString = [[NSString alloc] initWithData:responseObject encoding:NSUTF8StringEncoding];
// NSLog(@"success:%@", JSONString);
} failure:^(AFHTTPRequestOperation *operation,NSError *error) {
//请求失败
NSLog(@"Error: %@", error);
}];
}
#pragma mark - POST Request (iOS 6-7)
//POST请求
- (void)methodPostWithURL:(NSString *)urlString parameters:(NSDictionary *)parameters
{
//致空请求
if (manager) {
manager =
nil;
}
//添加参数
//创建请求
manager = [AFHTTPRequestOperationManagermanager];
//设置请求的解析器为AFHTTPResponseSerializer(用于直接解析数据NSData),默认为AFJSONResponseSerializer(用于解析JSON)
// manager.responseSerializer = [AFHTTPResponseSerializer serializer];
//发送POST请求
[manager POST:urlStringparameters:parameters
success:^(AFHTTPRequestOperation *operation,id responseObject) {
//请求成功(当解析器为AFJSONResponseSerializer时)
// NSLog(@"Success: %@", responseObject);
[self.delegatepassValue:responseObject];
//请求成功(当解析器为AFHTTPResponseSerializer时)
// NSString *JSONString = [[NSString alloc] initWithData:responseObject encoding:NSUTF8StringEncoding];
// NSLog(@"success:%@", JSONString);
} failure:^(AFHTTPRequestOperation *operation,NSError *error) {
//请求失败
NSLog(@"Error: %@", error);
}];
}
#pragma mark - Upload Request (iOS 6-7)
//上传(以表单方式上传,以图片为例)
- (void)methodUploadWithURL:(NSString *)urlString parameters:(NSDictionary *)parameters image:(UIImage *)image
{
//致空请求
if (manager) {
manager =
nil;
}
//添加参数
//创建请求
manager = [AFHTTPRequestOperationManagermanager];
//设置请求的解析器为AFHTTPResponseSerializer(用于直接解析数据NSData),默认为AFJSONResponseSerializer(用于解析JSON)
// manager.responseSerializer = [AFHTTPResponseSerializer serializer];
//发送POST请求,添加需要发送的文件,此处为图片
[manager POST:urlStringparameters:parameters
constructingBodyWithBlock:^(id<AFMultipartFormData> formData) {
//添加图片,并对其进行压缩(0.0为最大压缩率,1.0为最小压缩率)
NSData *imageData =
UIImageJPEGRepresentation(image, 1.0);
NSDateFormatter *formatter = [[NSDateFormatteralloc]
init];
//
设置时间格式
formatter.dateFormat =
@"yyyyMMddHHmmss";
NSString *str = [formatter
stringFromDate:[NSDate
date]];
NSString *fileName = [NSStringstringWithFormat:@"%@.png", str];
//添加要上传的文件,此处为图片
[formData appendPartWithFileData:imageData
name:@"uploadFile"
fileName:fileName
mimeType:@"image/jpeg"];
} success:^(AFHTTPRequestOperation *operation,id responseObject) {
//请求成功(当解析器为AFJSONResponseSerializer时)
NSLog(@"Success: %@", responseObject);
[self.delegatepassValue:responseObject];
//请求成功(当解析器为AFHTTPResponseSerializer时)
// NSString *JSONString = [[NSString alloc] initWithData:responseObject encoding:NSUTF8StringEncoding];
// NSLog(@"success:%@", JSONString);
} failure:^(AFHTTPRequestOperation *operation,NSError *error) {
//请求失败
NSLog(@"Error: %@", error);
}];
}
#pragma mark - Download Request (iOS 6-7)
//下载
- (void)methodDownload
{
/*
//下载进度条
UIProgressView *downProgressView = [[UIProgressView alloc] initWithProgressViewStyle:UIProgressViewStyleDefault];
downProgressView.center = CGPointMake(self.view.center.x, 220);
downProgressView.progress = 0;
downProgressView.progressTintColor = [UIColor blueColor];
downProgressView.trackTintColor = [UIColor grayColor];
[self.view addSubview:downProgressView];
//设置存放文件的位置(此Demo把文件保存在iPhone沙盒中的Documents文件夹中。关于如何获取文件路径,请自行搜索相关资料)
//方法一
// NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
// NSString *cachesDirectory = [paths objectAtIndex:0];
// NSString *filePath = [cachesDirectory stringByAppendingPathComponent:@"文件名"];
//方法二
NSString *filePath = [NSString stringWithFormat:@"%@/Documents/文件名(注意后缀名)", NSHomeDirectory()];
//打印文件保存的路径
NSLog(@"%@",filePath);
//创建请求管理
operation = [[AFHTTPRequestOperation alloc] initWithRequest:[NSURLRequest requestWithURL:[NSURL URLWithString:@"下载地址"]]];
//添加下载请求(获取服务器的输出流)
operation.outputStream = [NSOutputStream outputStreamToFileAtPath:filePath append:NO];
//设置下载进度条
[operation setDownloadProgressBlock:^(NSUInteger bytesRead, long long totalBytesRead, long long totalBytesExpectedToRead) {
//显示下载进度
CGFloat progress = ((float)totalBytesRead) / totalBytesExpectedToRead;
[downProgressView setProgress:progress animated:YES];
}];
//请求管理判断请求结果
[operation setCompletionBlockWithSuccess:^(AFHTTPRequestOperation *operation, id responseObject) {
//请求成功
NSLog(@"Finish and Download to: %@", filePath);
} failure:^(AFHTTPRequestOperation *operation, NSError *error) {
//请求失败
NSLog(@"Error: %@",error);
}];
*/
}
#pragma mark - Download Management (iOS 6-7)
//开始下载(断点续传)
- (void)downloadStart
{
[selfmethodDownload];
[operation
start];
}
//暂停下载(断点续传)
- (void)downloadPause
{
[operation
pause];
}
//继续下载(断点续传)
- (void)downloadResume
{
[operation
resume];
}
#pragma mark - Upload Request (iOS 7 only)
//上传(iOS7专用)
- (void)methodUploadFor7
{
//致空请求
if (sessionManager) {
sessionManager =nil;
}
//创建请求(iOS7专用)
sessionManager = [[AFURLSessionManageralloc]
initWithSessionConfiguration:[NSURLSessionConfigurationdefaultSessionConfiguration]];
//添加请求接口
NSURLRequest *request = [NSURLRequestrequestWithURL:[NSURLURLWithString:@"上传地址"]];
//添加上传的文件
NSURL *filePath = [NSURLfileURLWithPath:@"本地文件地址"];
//发送上传请求
NSURLSessionUploadTask *uploadTask = [sessionManageruploadTaskWithRequest:request
fromFile:filePath
progress:nilcompletionHandler:^(NSURLResponse *response,id responseObject,
NSError *error) {
if (error) {
//请求失败
NSLog(@"Error: %@", error);
} else {
//请求成功
NSLog(@"Success: %@ %@", response, responseObject);
}
}];
//开始上传
[uploadTask resume];
}
#pragma mark - Download Request (iOS 7 only)
//下载(iOS7专用)
- (void)methodDownloadFor7
{
//致空请求
if (sessionManager) {
sessionManager =nil;
}
//创建请求(iOS7专用)
sessionManager = [[AFURLSessionManageralloc]
initWithSessionConfiguration:[NSURLSessionConfigurationdefaultSessionConfiguration]];
//添加请求接口
NSURLRequest *request = [NSURLRequestrequestWithURL:[NSURLURLWithString:@"下载地址"]];
//发送下载请求
NSURLSessionDownloadTask *downloadTask = [sessionManagerdownloadTaskWithRequest:request
progress:nil
destination:^NSURL *(NSURL *targetPath,NSURLResponse *response) {
//设置存放文件的位置(此Demo把文件保存在iPhone沙盒中的Documents文件夹中。关于如何获取文件路径,请自行搜索相关资料)
NSURL *filePath = [NSURLfileURLWithPath:[NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,NSUserDomainMask,
YES)firstObject]];
return [filePathURLByAppendingPathComponent:[response
suggestedFilename]];
} completionHandler:^(NSURLResponse *response,NSURL *filePath,
NSError *error) {
//下载完成
NSLog(@"Finish and Download to: %@", filePath);
}];
//开始下载
[downloadTask resume];
}
@end
工程完美,自己复制可用
开始啦:
1:自定义网络请求DataRequestManager类专门管理网络用的
朋友们以下代码就可以直接复制来用了
.h文件
// DataRequestManager.h
// TestKeyBoard
// Created by mac on 14-10-21.
// Copyright (c) 2014年 mac. All rights reserved.
#import <Foundation/Foundation.h>
@protocol DataRequestManagerDelegate<NSObject>
//通过代理传值到需要的地方
- (void)passValue:(id)value;
@optional
- (void)passGetValue:(id)getValue;
@end
@interface DataRequestManager :
NSObject
{
AFHTTPRequestOperationManager *manager;//创建请求(iOS 6-7)
AFURLSessionManager *sessionManager;
//创建请求(iOS7专用)
AFHTTPRequestOperation *operation;
//创建请求管理(用于上传和下载)
}
@property (nonatomic,assign)
id<DataRequestManagerDelegate> delegate;
//GET请求调用方法
- (void)methodGetWithURL:(NSString *)urlString;
//POST请求调用方法
- (void)methodPostWithURL:(NSString *)urlString parameters:(NSDictionary *)parameters;
//上传图片
- (void)methodUploadWithURL:(NSString *)urlString parameters:(NSDictionary *)parameters image:(UIImage *)image;
@end
.m文件
// DataRequestManager.m
// TestKeyBoard
//
// Created by mac on 14-10-21.
// Copyright (c) 2014年 mac. All rights reserved.
//
#import "DataRequestManager.h"
#import "AFNetworking.h"
@implementation DataRequestManager
//GET请求
- (void)methodGetWithURL:(NSString *)urlString
{
//致空请求
if (manager) {
manager =
nil;
}
//创建请求
manager = [AFHTTPRequestOperationManagermanager];
//设置请求的解析器为AFHTTPResponseSerializer(用于直接解析数据NSData),默认为AFJSONResponseSerializer(用于解析JSON)
// manager.responseSerializer = [AFHTTPResponseSerializer serializer];
//发送GET请求
[manager GET:urlStringparameters:nilsuccess:^(AFHTTPRequestOperation
*operation,id responseObject) {
//请求成功(当解析器为AFJSONResponseSerializer时)
NSLog(@"getSuccess: %@", responseObject);
[self.delegatepassGetValue:responseObject];
//请求成功(当解析器为AFHTTPResponseSerializer时)
// NSString *JSONString = [[NSString alloc] initWithData:responseObject encoding:NSUTF8StringEncoding];
// NSLog(@"success:%@", JSONString);
} failure:^(AFHTTPRequestOperation *operation,NSError *error) {
//请求失败
NSLog(@"Error: %@", error);
}];
}
#pragma mark - POST Request (iOS 6-7)
//POST请求
- (void)methodPostWithURL:(NSString *)urlString parameters:(NSDictionary *)parameters
{
//致空请求
if (manager) {
manager =
nil;
}
//添加参数
//创建请求
manager = [AFHTTPRequestOperationManagermanager];
//设置请求的解析器为AFHTTPResponseSerializer(用于直接解析数据NSData),默认为AFJSONResponseSerializer(用于解析JSON)
// manager.responseSerializer = [AFHTTPResponseSerializer serializer];
//发送POST请求
[manager POST:urlStringparameters:parameters
success:^(AFHTTPRequestOperation *operation,id responseObject) {
//请求成功(当解析器为AFJSONResponseSerializer时)
// NSLog(@"Success: %@", responseObject);
[self.delegatepassValue:responseObject];
//请求成功(当解析器为AFHTTPResponseSerializer时)
// NSString *JSONString = [[NSString alloc] initWithData:responseObject encoding:NSUTF8StringEncoding];
// NSLog(@"success:%@", JSONString);
} failure:^(AFHTTPRequestOperation *operation,NSError *error) {
//请求失败
NSLog(@"Error: %@", error);
}];
}
#pragma mark - Upload Request (iOS 6-7)
//上传(以表单方式上传,以图片为例)
- (void)methodUploadWithURL:(NSString *)urlString parameters:(NSDictionary *)parameters image:(UIImage *)image
{
//致空请求
if (manager) {
manager =
nil;
}
//添加参数
//创建请求
manager = [AFHTTPRequestOperationManagermanager];
//设置请求的解析器为AFHTTPResponseSerializer(用于直接解析数据NSData),默认为AFJSONResponseSerializer(用于解析JSON)
// manager.responseSerializer = [AFHTTPResponseSerializer serializer];
//发送POST请求,添加需要发送的文件,此处为图片
[manager POST:urlStringparameters:parameters
constructingBodyWithBlock:^(id<AFMultipartFormData> formData) {
//添加图片,并对其进行压缩(0.0为最大压缩率,1.0为最小压缩率)
NSData *imageData =
UIImageJPEGRepresentation(image, 1.0);
NSDateFormatter *formatter = [[NSDateFormatteralloc]
init];
//
设置时间格式
formatter.dateFormat =
@"yyyyMMddHHmmss";
NSString *str = [formatter
stringFromDate:[NSDate
date]];
NSString *fileName = [NSStringstringWithFormat:@"%@.png", str];
//添加要上传的文件,此处为图片
[formData appendPartWithFileData:imageData
name:@"uploadFile"
fileName:fileName
mimeType:@"image/jpeg"];
} success:^(AFHTTPRequestOperation *operation,id responseObject) {
//请求成功(当解析器为AFJSONResponseSerializer时)
NSLog(@"Success: %@", responseObject);
[self.delegatepassValue:responseObject];
//请求成功(当解析器为AFHTTPResponseSerializer时)
// NSString *JSONString = [[NSString alloc] initWithData:responseObject encoding:NSUTF8StringEncoding];
// NSLog(@"success:%@", JSONString);
} failure:^(AFHTTPRequestOperation *operation,NSError *error) {
//请求失败
NSLog(@"Error: %@", error);
}];
}
#pragma mark - Download Request (iOS 6-7)
//下载
- (void)methodDownload
{
/*
//下载进度条
UIProgressView *downProgressView = [[UIProgressView alloc] initWithProgressViewStyle:UIProgressViewStyleDefault];
downProgressView.center = CGPointMake(self.view.center.x, 220);
downProgressView.progress = 0;
downProgressView.progressTintColor = [UIColor blueColor];
downProgressView.trackTintColor = [UIColor grayColor];
[self.view addSubview:downProgressView];
//设置存放文件的位置(此Demo把文件保存在iPhone沙盒中的Documents文件夹中。关于如何获取文件路径,请自行搜索相关资料)
//方法一
// NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
// NSString *cachesDirectory = [paths objectAtIndex:0];
// NSString *filePath = [cachesDirectory stringByAppendingPathComponent:@"文件名"];
//方法二
NSString *filePath = [NSString stringWithFormat:@"%@/Documents/文件名(注意后缀名)", NSHomeDirectory()];
//打印文件保存的路径
NSLog(@"%@",filePath);
//创建请求管理
operation = [[AFHTTPRequestOperation alloc] initWithRequest:[NSURLRequest requestWithURL:[NSURL URLWithString:@"下载地址"]]];
//添加下载请求(获取服务器的输出流)
operation.outputStream = [NSOutputStream outputStreamToFileAtPath:filePath append:NO];
//设置下载进度条
[operation setDownloadProgressBlock:^(NSUInteger bytesRead, long long totalBytesRead, long long totalBytesExpectedToRead) {
//显示下载进度
CGFloat progress = ((float)totalBytesRead) / totalBytesExpectedToRead;
[downProgressView setProgress:progress animated:YES];
}];
//请求管理判断请求结果
[operation setCompletionBlockWithSuccess:^(AFHTTPRequestOperation *operation, id responseObject) {
//请求成功
NSLog(@"Finish and Download to: %@", filePath);
} failure:^(AFHTTPRequestOperation *operation, NSError *error) {
//请求失败
NSLog(@"Error: %@",error);
}];
*/
}
#pragma mark - Download Management (iOS 6-7)
//开始下载(断点续传)
- (void)downloadStart
{
[selfmethodDownload];
[operation
start];
}
//暂停下载(断点续传)
- (void)downloadPause
{
[operation
pause];
}
//继续下载(断点续传)
- (void)downloadResume
{
[operation
resume];
}
#pragma mark - Upload Request (iOS 7 only)
//上传(iOS7专用)
- (void)methodUploadFor7
{
//致空请求
if (sessionManager) {
sessionManager =nil;
}
//创建请求(iOS7专用)
sessionManager = [[AFURLSessionManageralloc]
initWithSessionConfiguration:[NSURLSessionConfigurationdefaultSessionConfiguration]];
//添加请求接口
NSURLRequest *request = [NSURLRequestrequestWithURL:[NSURLURLWithString:@"上传地址"]];
//添加上传的文件
NSURL *filePath = [NSURLfileURLWithPath:@"本地文件地址"];
//发送上传请求
NSURLSessionUploadTask *uploadTask = [sessionManageruploadTaskWithRequest:request
fromFile:filePath
progress:nilcompletionHandler:^(NSURLResponse *response,id responseObject,
NSError *error) {
if (error) {
//请求失败
NSLog(@"Error: %@", error);
} else {
//请求成功
NSLog(@"Success: %@ %@", response, responseObject);
}
}];
//开始上传
[uploadTask resume];
}
#pragma mark - Download Request (iOS 7 only)
//下载(iOS7专用)
- (void)methodDownloadFor7
{
//致空请求
if (sessionManager) {
sessionManager =nil;
}
//创建请求(iOS7专用)
sessionManager = [[AFURLSessionManageralloc]
initWithSessionConfiguration:[NSURLSessionConfigurationdefaultSessionConfiguration]];
//添加请求接口
NSURLRequest *request = [NSURLRequestrequestWithURL:[NSURLURLWithString:@"下载地址"]];
//发送下载请求
NSURLSessionDownloadTask *downloadTask = [sessionManagerdownloadTaskWithRequest:request
progress:nil
destination:^NSURL *(NSURL *targetPath,NSURLResponse *response) {
//设置存放文件的位置(此Demo把文件保存在iPhone沙盒中的Documents文件夹中。关于如何获取文件路径,请自行搜索相关资料)
NSURL *filePath = [NSURLfileURLWithPath:[NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,NSUserDomainMask,
YES)firstObject]];
return [filePathURLByAppendingPathComponent:[response
suggestedFilename]];
} completionHandler:^(NSURLResponse *response,NSURL *filePath,
NSError *error) {
//下载完成
NSLog(@"Finish and Download to: %@", filePath);
}];
//开始下载
[downloadTask resume];
}
@end
工程完美,自己复制可用
相关文章推荐
- iOS经验1:自己写的网络数据请求 第三方框架 断点续传 上传下载
- 网络请求工具类之OkHttp3封装(支持缓存、日志、拦截器、断点下载、上传等)
- 【iOS开发-96】网络请求总结,深浅拷贝copy和mutableCopy,SDWebImage图像下载第三方框架
- iOS基础8:自定义MyData/自定义SQLite用于网络判断,版本判断,图片缓存处理,下载或者上传的GET或POST请求,加密手段,.数据解析
- AFN详解(检测网络状态,下载,上传,数据请求)
- iOS开发——网络篇——文件下载(NSMutableData、NSFileHandle、NSOutputStream)和上传、压缩和解压(三方框架ZipArchive),请求头和请求体格式,断点续传Range
- 网络数据请求实践一:android-async-http实现下载和上传
- ASIHTTPRequest发送Get、Post请求,断点下载,上传,判断网络状态
- Android 利用an框架快速实现网络请求(含下载上传文件)
- 网络数据请求实践一:android-async-http实现下载和上传
- 网络数据请求实践一:android-async-http实现下载和上传
- Android网络请求 上传文件 和 下载文件 断点下载
- Android大数据、断点续传、耗时下载之DownloadManager开发简介(1)
- 利用ASIHttpRequest框架进行网络数据请求(一)—— 利用get请求数据
- AIR文件上传与文件断点续传方式下载
- ASIHttpRequest:创建队列、下载请求、断点续传、解压缩
- iOS-网络编程 文件上传和断点离线下载
- 使用AsyncHttpClient框架来完成网络数据的请求
- AFNetWorking的简单封装 图片音频 视频下载 上传 请求数据
- Java网络编程:实现HTTP断点续传下载工具(附源代码)