版权声明:本文为博主原创文章。未经博主同意不得转载。

https://blog.csdn.net/quanqinayng/article/details/37659751

.h文件 

//
// HttpUtil.h
// SmallTaurus
//
// Created by Fuer on 14-7-7.
// Copyright (c) 2014年 FuEr. All rights reserved.
//
/**
* 对ASI的封装
*/
#import <Foundation/Foundation.h>
#import "ASIHTTPRequest.h"
#import "ASIFormDataRequest.h"
/**
* Debug_LOG信息控制;
*
* IS_ENABLE_DEBUG_LOG 设置为 1 ,打印请求log基本信息;
* IS_ENABLE_DEBUG_LOG 设置为 0 ,不打印请求log基本信息;
*/
#define IS_ENABLE_DEBUG_LOG 1 #if IS_ENABLE_DEBUG_LOG
#define kDEBUG_LOG() NSLog(@"line:(%d),%s",__LINE__,__FUNCTION__)
#define kNSLog(...) NSLog(__VA_ARGS__)
#else
#define kDEBUG_LOG()
#define kNSLog(...)
#endif extern NSString *const kAPI_BASE_URL; /**
* ASICLient 请求回调的块声明。
*
* 主要的请求完毕,失败,上传及下载进度 Block回调;
*/
typedef void (^KKCompletedBlock)(id JSON,NSString *stringData);
typedef void (^KKFailedBlock)(NSError *error);
typedef void (^KKProgressBlock)(float progress); @interface HttpUtil : NSObject
+(HttpUtil*)shareInstance;
/**
* 一般的get请求,无參数;
*
* @param path 接口路径。不能为空;
* @param completeBlock 请求完毕块。返回 id JSON, NSString *stringData;
* @param failed 请求失败块。返回 NSError *error;
*
* @return 返回ASIHTTPRequest的指针,可用于 NSOperationQueue操作。
*/
+ (ASIHTTPRequest *)GET_Path:(NSString *)path completed:(KKCompletedBlock )completeBlock failed:(KKFailedBlock )failed; /**
* 一般的GET请求。有參数。
*
* @param path 接口路径,不能为空;
* @param paramsDic 请求的參数的字典,參数可为nil, 比如:NSDictionary *params = @{@"key":@"value"}
* @param completeBlock 请求完毕块,返回 id JSON, NSString *stringData;
* @param failed 请求失败块,返回 NSError *error;
*
* @return 返回ASIHTTPRequest的指针,可用于 NSOperationQueue操作
*/
+ (ASIHTTPRequest *)GET_Path:(NSString *)path params:(NSDictionary *)paramsDic completed:(KKCompletedBlock )completeBlock failed:(KKFailedBlock )failed; /**
* 一般的POST请求,有參数;
*
* @param path 接口路径。不能为空。
* @param paramsDic 请求的參数的字典,參数可为nil, 比如:NSDictionary *params = @{@"key":@"value"}
* @param completeBlock 请求完毕块。返回 id JSON, NSString *stringData;
* @param failed 请求失败块,返回 NSError *error;
*
* @return 返回ASIHTTPRequest的指针。可用于 NSOperationQueue操作
*/
+ (ASIHTTPRequest *)POST_Path:(NSString *)path params:(NSDictionary *)paramsDic completed:(KKCompletedBlock )completeBlock failed:(KKFailedBlock )failed; /**
* 一般GET请求下载文件;
*
* @param path 接口路径,不能为空;
* @param destination 下载文件保存的路径,不能为空;
* @param name 下载文件保存的名字,不能为空;
* @param progressBlock 下载文件的Progress块,返回 float progress,在此跟踪下载进度。
* @param completeBlock 请求完毕块,无返回值。
* @param failed 请求失败块,返回 NSError *error;
*
* @return 返回ASIHTTPRequest的指针,可用于 NSOperationQueue操作
*/
+ (ASIHTTPRequest *)DownFile_Path:(NSString *)path writeTo:(NSString *)destination fileName:(NSString *)name setProgress:(KKProgressBlock)progressBlock completed:(ASIBasicBlock)completedBlock failed:(KKFailedBlock )failed; /**
* 一般的POST上传文件;
*
* @param path 上传接口路径。不能为空;
* @param filePath 要上传的文件路径,不能为空;
* @param fileKey 上传文件相应server接收的key,不能为空;
* @param params 请求的參数的字典,參数可为nil, 比如:NSDictionary *params = @{@"key":@"value"}
* @param progressBlock 上传文件的Progress块,返回 float progress,在此跟踪下载进度;
* @param completeBlock 请求完毕块,返回 id JSON, NSString *stringData;
* @param failed 请求失败块,返回 NSError *error;
*
* @return 返回ASIHTTPRequest的指针,可用于 NSOperationQueue操作
*/
+ (ASIHTTPRequest *)UploadFile_Path:(NSString *)path file:(NSString *)filePath forKey:(NSString *)fileKey params:(NSDictionary *)params SetProgress:(KKProgressBlock )progressBlock completed:(KKCompletedBlock )completedBlock failed:(KKFailedBlock )failed; /**
* 一般的POST数据Data上传。
*
* @param path 上传接口路径。不能为空;
* @param fData 要上传的文件Data,不能为空;
* @param dataKey 上传的Data相应server接收的key,不能为空;
* @param params 请求的參数的字典,參数可为nil, 比如:NSDictionary *params = @{@"key":@"value"}
* @param progressBlock 上传文件的Progress块,返回 float progress,在此跟踪下载进度。
* @param completeBlock 请求完毕块,返回 id JSON, NSString *stringData;
* @param failed 请求失败块。返回 NSError *error;
*
* @return 返回ASIHTTPRequest的指针,可用于 NSOperationQueue操作
*/
+ (ASIHTTPRequest *)UploadData_Path:(NSString *)path fileData:(NSData *)fData forKey:(NSString *)dataKey params:(NSDictionary *)params SetProgress:(KKProgressBlock )progressBlock completed:(KKCompletedBlock )completedBlock failed:(KKFailedBlock )failed; /**
* 文件下载。支持断点续传功能;
*
* @param path 接口路径,不能为空;
* @param destinationPath 下载文件要保存的路径。不能为空;
* @param tempPath 暂时文件保存的路径。不能为空;
* @param name 下载保存的文件名称。不能为空。
* @param progressBlock 下载文件的Progress块。返回 float progress,在此跟踪下载进度。
* @param completedBlock 下载完毕回调块,无回返值。
* @param failed 下载失败回调块,返回 NSError *error;
*
* @return 返回ASIHTTPRequest的指针,可用于 NSOperationQueue操作
*/
+ (ASIHTTPRequest *)ResumeDown_Path:(NSString *)path writeTo:(NSString *)destinationPath tempPath:(NSString *)tempPath fileName:(NSString *)name setProgress:(KKProgressBlock )progressBlock completed:(ASIBasicBlock )completedBlock failed:(KKFailedBlock )failed; /*
安装:配置
1:所需frame.work;
CFNetwork, SystemConfiguration, MobileCoreServices, CoreGraphics and libz.dylib libxml2.dylib
2: ASI Tests 须要 https://github.com/gh-unit/gh-unit/tree/master 然后导入 :GHUnitIOS.framework
3:bulid setting Header search path 加入 /usr/include/libxml2
4:在 test/ASIDataCompareTest.m中有个 NStask错误,删除文件就可以;
5: 假设使用 Test文件加里面的东西。使用 GHUnitIOS.framework http://stackoverflow.com/questions/13925437/ghunitios-ghunit-h-file-not-found-in-xcode 官方文档:http://allseeing-i.com/ASIHTTPRequest/How-to-use */
@end

.m文件

//
// HttpUtil.m
// SmallTaurus
//
// Created by Fuer on 14-7-7.
// Copyright (c) 2014年 FuEr. All rights reserved.
// #import "HttpUtil.h"
NSString *const kAPI_BASE_URL = @"http://api.douban.com/v2/"; @implementation HttpUtil
+(HttpUtil*)shareInstance
{
static HttpUtil *httpUtil = nil;
static dispatch_once_t onceToken;
dispatch_once(&onceToken, ^{
httpUtil = [[HttpUtil alloc]init];
});
return httpUtil;
}
+ (ASIHTTPRequest *)GET_Path:(NSString *)path completed:(KKCompletedBlock )completeBlock failed:(KKFailedBlock )failed
{
NSString *urlStr = [NSString stringWithFormat:@"%@%@",kAPI_BASE_URL,path];
urlStr = [urlStr stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
NSURL *url = [NSURL URLWithString:urlStr];
__weak ASIHTTPRequest *request = [ASIHTTPRequest requestWithURL:url];
request.requestMethod = @"GET"; [request setCompletionBlock:^{
NSError *errorForJSON = [NSError errorWithDomain:@"请求数据解析为json格式。发出错误" code:2014 userInfo:@{@"请求数据json解析错误": @"中文",@"serial the data to json error":@"English"}];
id jsonData = [NSJSONSerialization JSONObjectWithData:[request responseData] options:0 error:&errorForJSON];
completeBlock(jsonData,request.responseString);
}]; [request setFailedBlock:^{
failed([request error]);
}]; [request startAsynchronous]; kNSLog(@"ASIClient GET: %@",[request url]); return request;
} + (ASIHTTPRequest *)GET_Path:(NSString *)path params:(NSDictionary *)paramsDic completed:(KKCompletedBlock )completeBlock failed:(KKFailedBlock )failed
{
NSMutableString *paramsString = [NSMutableString stringWithCapacity:1];
[paramsDic enumerateKeysAndObjectsUsingBlock:^(id key, id obj, BOOL *stop) {
[paramsString appendFormat:@"%@=%@",key,obj];
[paramsString appendString:@"&"];
}];
NSString *urlStr = [NSString stringWithFormat:@"%@%@?%@",kAPI_BASE_URL,path,paramsString];
urlStr = [urlStr substringToIndex:urlStr.length-1];
urlStr = [urlStr stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding]; NSURL *url = [NSURL URLWithString:urlStr];
__weak ASIHTTPRequest *request = [ASIHTTPRequest requestWithURL:url];
request.requestMethod = @"GET"; [request setCompletionBlock:^{
NSError *errorForJSON = [NSError errorWithDomain:@"请求数据解析为json格式,发出错误" code:2014 userInfo:@{@"请求数据json解析错误": @"中文",@"serial the data to json error":@"English"}];
id jsonData = [NSJSONSerialization JSONObjectWithData:[request responseData] options:0 error:&errorForJSON];
completeBlock(jsonData,request.responseString);
}]; [request setFailedBlock:^{
failed([request error]);
}]; [request startAsynchronous]; kNSLog(@"ASIClient GET: %@",[request url]); return request;
} + (ASIHTTPRequest *)POST_Path:(NSString *)path params:(NSDictionary *)paramsDic completed:(KKCompletedBlock )completeBlock failed:(KKFailedBlock )failed
{
NSString *urlStr = [NSString stringWithFormat:@"%@%@",kAPI_BASE_URL,path];
urlStr = [urlStr stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
NSURL *url = [NSURL URLWithString:urlStr];
__weak ASIFormDataRequest *request = [ASIFormDataRequest requestWithURL:url];
request.requestMethod = @"POST"; [paramsDic enumerateKeysAndObjectsUsingBlock:^(id key, id obj, BOOL *stop) {
[request setPostValue:obj forKey:key];
}]; [request setCompletionBlock:^{
NSError *errorForJSON = [NSError errorWithDomain:@"请求数据解析为json格式,发出错误" code:2014 userInfo:@{@"请求数据json解析错误": @"中文",@"serial the data to json error":@"English"}];
id jsonData = [NSJSONSerialization JSONObjectWithData:[request responseData] options:0 error:&errorForJSON];
completeBlock(jsonData,request.responseString);
}]; [request setFailedBlock:^{
failed([request error]);
}]; [request startAsynchronous]; kNSLog(@"ASIClient POST: %@ %@",[request url],paramsDic); return request;
} + (ASIHTTPRequest *)DownFile_Path:(NSString *)path writeTo:(NSString *)destination fileName:(NSString *)name setProgress:(KKProgressBlock)progressBlock completed:(ASIBasicBlock)completedBlock failed:(KKFailedBlock )failed
{
__weak ASIHTTPRequest *request = [ASIHTTPRequest requestWithURL:[NSURL URLWithString:path]];
NSString *filePath = nil;
if ([destination hasSuffix:@"/"]) {
filePath = [NSString stringWithFormat:@"%@%@",destination,name];
}
else
{
filePath = [NSString stringWithFormat:@"%@/%@",destination,name];
}
[request setDownloadDestinationPath:filePath]; __block float downProgress = 0;
[request setBytesReceivedBlock:^(unsigned long long size, unsigned long long total) {
downProgress += (float)size/total;
progressBlock(downProgress);
}]; [request setCompletionBlock:^{
downProgress = 0;
completedBlock();
}]; [request setFailedBlock:^{
failed([request error]);
}]; [request startAsynchronous]; kNSLog(@"ASIClient 下载文件:%@ ",path);
kNSLog(@"ASIClient 保存路径:%@",filePath); return request;
} + (ASIHTTPRequest *)UploadFile_Path:(NSString *)path file:(NSString *)filePath forKey:(NSString *)fileKey params:(NSDictionary *)params SetProgress:(KKProgressBlock )progressBlock completed:(KKCompletedBlock )completedBlock failed:(KKFailedBlock )failed
{ NSURL *url = [NSURL URLWithString:path];
__weak ASIFormDataRequest *request = [ASIFormDataRequest requestWithURL:url];
[request setFile:filePath forKey:fileKey];
if (params.count > 0) {
[params enumerateKeysAndObjectsUsingBlock:^(id key, id obj, BOOL *stop) {
[request setPostValue:obj forKey:key];
}];
} __block float upProgress = 0;
[request setBytesSentBlock:^(unsigned long long size, unsigned long long total) {
upProgress += (float)size/total;
progressBlock(upProgress);
}]; [request setCompletionBlock:^{
upProgress=0;
NSError *errorForJSON = [NSError errorWithDomain:@"请求数据解析为json格式。发出错误" code:2014 userInfo:@{@"请求数据json解析错误": @"中文",@"serial the data to json error":@"English"}];
id jsonData = [NSJSONSerialization JSONObjectWithData:[request responseData] options:0 error:&errorForJSON];
completedBlock(jsonData,[request responseString]);
}]; [request setFailedBlock:^{
failed([request error]);
}]; [request startAsynchronous]; kNSLog(@"ASIClient 文件上传:%@ file=%@ key=%@",path,filePath,fileKey);
kNSLog(@"ASIClient 文件上传參数:%@",params); return request;
} + (ASIHTTPRequest *)UploadData_Path:(NSString *)path fileData:(NSData *)fData forKey:(NSString *)dataKey params:(NSDictionary *)params SetProgress:(KKProgressBlock )progressBlock completed:(KKCompletedBlock )completedBlock failed:(KKFailedBlock )failed
{
NSURL *url = [NSURL URLWithString:path];
__weak ASIFormDataRequest *request = [ASIFormDataRequest requestWithURL:url];
[request setData:fData forKey:dataKey];
if (params.count > 0) {
[params enumerateKeysAndObjectsUsingBlock:^(id key, id obj, BOOL *stop) {
[request setPostValue:obj forKey:key];
}];
} __block float upProgress = 0;
[request setBytesSentBlock:^(unsigned long long size, unsigned long long total) {
upProgress += (float)size/total;
progressBlock(upProgress);
}]; [request setCompletionBlock:^{
upProgress=0;
NSError *errorForJSON = [NSError errorWithDomain:@"请求数据解析为json格式,发出错误" code:2014 userInfo:@{@"请求数据json解析错误": @"中文",@"serial the data to json error":@"English"}];
id jsonData = [NSJSONSerialization JSONObjectWithData:[request responseData] options:0 error:&errorForJSON];
completedBlock(jsonData,[request responseString]);
}]; [request setFailedBlock:^{
failed([request error]);
}]; [request startAsynchronous]; kNSLog(@"ASIClient 文件上传:%@ size=%.2f MB key=%@",path,fData.length/1024.0/1024.0,dataKey);
kNSLog(@"ASIClient 文件上传參数:%@",params); return request;
} + (ASIHTTPRequest *)ResumeDown_Path:(NSString *)path writeTo:(NSString *)destinationPath tempPath:(NSString *)tempPath fileName:(NSString *)name setProgress:(KKProgressBlock )progressBlock completed:(ASIBasicBlock )completedBlock failed:(KKFailedBlock )failed
{
__weak ASIHTTPRequest *request = [ASIHTTPRequest requestWithURL:[NSURL URLWithString:path]];
NSString *filePath = nil;
if ([destinationPath hasSuffix:@"/"]) {
filePath = [NSString stringWithFormat:@"%@%@",destinationPath,name];
}
else
{
filePath = [NSString stringWithFormat:@"%@/%@",destinationPath,name];
} [request setDownloadDestinationPath:filePath]; NSString *tempForDownPath = nil;
if ([tempPath hasSuffix:@"/"]) {
tempForDownPath = [NSString stringWithFormat:@"%@%@.download",tempPath,name];
}
else
{
tempForDownPath = [NSString stringWithFormat:@"%@/%@.download",tempPath,name];
} [request setTemporaryFileDownloadPath:tempForDownPath];
[request setAllowResumeForFileDownloads:YES]; __block float downProgress = 0;
downProgress = [[NSUserDefaults standardUserDefaults] floatForKey:@"ASIClient_ResumeDOWN_PROGRESS"];
[request setBytesReceivedBlock:^(unsigned long long size, unsigned long long total) {
downProgress += (float)size/total;
if (downProgress >1.0) {
downProgress=1.0;
}
[[NSUserDefaults standardUserDefaults] setFloat:downProgress forKey:@"ASIClient_ResumeDOWN_PROGRESS"];
progressBlock(downProgress);
}]; [request setCompletionBlock:^{
downProgress = 0;
[[NSUserDefaults standardUserDefaults] setFloat:downProgress forKey:@"ASIClient_ResumeDOWN_PROGRESS"];
completedBlock();
if ([[NSFileManager defaultManager] fileExistsAtPath:tempForDownPath]) {
//NSError *errorForDelete = [NSError errorWithDomain:@"删除暂时文件错误发生!" code:2015 userInfo:@{@"删除暂时文件错误发生": @"中文",@"delete the temp fife error":@"English"}];
//[[NSFileManager defaultManager] removeItemAtPath:tempForDownPath error:&errorForDelete];
kNSLog(@"l %d> %s",__LINE__,__func__);
}
}]; [request setFailedBlock:^{
failed([request error]);
}]; [request startAsynchronous]; kNSLog(@"ASIClient 下载文件:%@ ",path);
kNSLog(@"ASIClient 保存路径:%@",filePath);
if (downProgress >0 && downProgress) {
if (downProgress >=1.0) downProgress = 0.9999;
kNSLog(@"ASIClient 上次下载已完毕:%.2f/100",downProgress*100);
}
return request;
}
@end

在使用这个时候。注意NSJSONSerialization的options參数。

对ASIHTTPRequest的封装的更多相关文章

  1. 用Block封装ASIHttpRequest

    用Block封装ASIHttpRequest 横方便的网络请求方法,不用每次都写代理方法.使代码先得很整齐,不会凌乱. 接口部分: // // LYHASIRequestBlock.h // ASIB ...

  2. ASIHttpRequest封装

    ASIHttpRequest是一个非常好的库,只是直接使用稍嫌麻烦,以下就尝试来封装一下吧. 思路:每次请求时,须要创建一个ASIHttpRequest对象,设置它的属性(url,delegate.p ...

  3. 基于ASIHTTPRequest封装的HttpClient

    ASIHTTPRequest作为一个比较知名的http访问库本身功能比较强大,在项目开发过程中,如果每个请求,都要使用ASIHTTPRequest来写,有以下几个弊端: (1)繁琐,无封装性. (2) ...

  4. 强大的HTTP包装开源项目ASIHTTPRequest介绍

    ASIHTTPRequest 是一个直接在CFNetwork上做的开源项目,提供了一个比官方更方便更强大的HTTP网络传输的封装.它的特色功能如下: 1,下载的数据直接保存到内存或文件系统里 2,提供 ...

  5. ASIHTTPRequest详解 [经典]

    ASIHTTPRequest 对CFNetwork API进行了封装,并且使用起来非常简单,用Objective-C编写,可以很好的应用在Mac OS X系统和iOS平台的应用程序中.ASIHTTPR ...

  6. IOS学习笔记25—HTTP操作之ASIHTTPRequest

    IOS学习笔记25—HTTP操作之ASIHTTPRequest 分类: iOS2012-08-12 10:04 7734人阅读 评论(3) 收藏 举报 iosios5网络wrapper框架新浪微博 A ...

  7. ASIHTTPRequest类库简介和使用说明

    官方网站: http://allseeing-i.com/ASIHTTPRequest/ .可以从上面下载到最新源码,以及获取到相关的资料. 使用iOS SDK中的HTTP网络请求API,相当的复杂, ...

  8. iOS通过ASIHTTPRequest提交JSON数据

    先验知识——什么是ASIHTTPRequest? 使用iOS SDK中的HTTP网络请求API,相当的复杂,调用很繁琐,ASIHTTPRequest就是一个对CFNetwork API进行了封装,并且 ...

  9. iOS - ASIHTTPRequest 网络请求

    前言 使用 iOS SDK 中的 HTTP 网络请求 API,相当的复杂,调用很繁琐,ASIHTTPRequest 就是一个对 CFNetwork API 进行了封装,并且使用起来非常简单的一套 AP ...

随机推荐

  1. linux学习笔记7---命令cp

    cp命令用来复制文件或者目录,是Linux系统中最常用的命令之一. cp命令用来将一个或多个源文件或者目录复制到指定的目的文件或目录.它可以将单个源文件复制成一个指定文件名的具体的文件或一个已经存在的 ...

  2. 在CentOS 7上利用systemctl添加自定义系统服务 /usr/lib/systemd/

    在CentOS 7上利用systemctl添加自定义系统服务[日期:2014-07-21] 来源:blog.csdn.net/yuanguozhengjust 作者:yuanguozhengjust ...

  3. python笔记5:装饰器、内置函数、json

    装饰器 装饰器本质上是一个Python函数,它可以让其他函数在不需要做任何代码变动的前提下增加额外功能,装饰器的返回值也是一个函数对象. 先看简单例子: def run(): time.sleep(1 ...

  4. SQL Server 2008 SP3简体中文版官方下载

    微软日前公开发布了SQL Server 2008 SP3,用户可以从微软下载中心获取SP服务包和功能包升级.SP3主要包括自SQL Server 2008 SP2以来的累积更新,修复了用户反馈的一些问 ...

  5. asp.net知识汇总-页面跳转Server.Transfer和Response.Redirect

    1. Server.Transfer 服务器端跳转 webform1.aspx跳转到webform2.aspx页面 webform1.aspx代码如下: protected void Page_Loa ...

  6. JavaWeb——过滤器

    过滤器简介 WEB过滤器是一个服务器端的组件,它可以截取用户端的请求与相应信息,并对这些信息过滤. 过滤器的工作原理和生命周期 在没有Web过滤器的情况下,用户直接访问服务器上的Web资源.但是如果存 ...

  7. EEPlat的基于浏览器的在线开发技术

    EEPlat的开发内容主要包含配置开发和基于API的扩展开发两块内容. EEPlat的配置开发基于后台的配置环境.直接通过界面操作配置就可以. EEPlat的配置平台是用EEPlat自解释构建的.本身 ...

  8. XmLHttpRequst下载Excel

    //得到浏览器版本 myJqHelp.getBrowser = function () { var ua = window.navigator.userAgent; var isIE = !!wind ...

  9. ChemDraw进行自动调整的步骤

    说到化学绘图软件那就不得不提ChemDraw,起非常的经典在国内外都得到了普遍应用,最新版是ChemDraw 15.1 Pro.在使用ChemDraw化学绘图工具绘制化学图形的时候,需要循序渐进一步一 ...

  10. 主流数据文件类型(.dat/.txt/.json/.csv)导入到python

    手写很累,复制的同学请点赞犒劳下在下哦 ^_^ 一.对于.CSV类型的数据 它们的数据导入都很简单 且看下面一顿操作: 我平时一般是读取整个文件,直接这样就可以了: import pandas as ...