不需要实例化HttpClient类,使用静态的HttpClient类函数来完成所有的HTTP请求。 不需要实例化HttpClient类,只需使用静态的HttpClient类函数来完成所有请求。
使用block来完成回调,并且可以监视下载&上传的过程。 使用block来完成回调,并且可以监视上传&下载的过程。
支持全局的HTTP请求环境设置,并且可以自定义HTTP请求。 支持全局的HTTP请求环境设置,并且可以自定义HTTP请求。
支持基于URL的缓存功能,并且可以清除缓存。 支持基于URL的缓存功能,并且可以清除缓存。
可以根据token取消请求,或者取消所有请求。 可以根据token取消请求,或者取消所有请求。
支持函数式编程。 支持函数式编程。
HttpClient.setGlobalCachePolicy(NSURLRequestCachePolicy.UseProtocolCachePolicy) //set the GlobalCachePolicy
//设置全局的缓存策略
HttpClient.setGlobalNeedSendParametersAsJSON(false) // set need set parameters as json
//设置是否以Json格式发送数据
HttpClient.setGlobalUsername("yourUserName") //Set the global authentication username
//设置全局的认证用户名
HttpClient.setGlobalPassword("123456") //Set the global authentication password
//设置全局的认证密码
HttpClient.setGlobalTimeoutInterval(40) //Set the global Http request time out
//设置全局的请求超期时间
HttpClient.setGlobalUserAgent("Firefox") // set useragent
//设置全局的UserAgeng
GlobalCachePolicy//(default value is NSURLRequestCachePolicy.UseProtocolCachePolicy ),
GlobalCachePolicy//(默认是NSURLRequestCachePolicy.UseProtocolCachePolicy ),
GlobalNeedSendParametersAsJSON//(the default value is false),
GlobalNeedSendParametersAsJSON//(默认是 is false),
GlobalTimeoutInterval//(the default value is 20),
GlobalTimeoutInterval//(默认是 is 20),
GlobalUserAgent//(the default value is HttpClient)
GlobalUserAgent//(默认是 is HttpClient)
private init(address:String,method:httpMethod,parameters:Dictionary<String,AnyObject>?, cache:Int,cancelToken:String?,queryPara:Dictionary<String,AnyObject>?, requestOptions:Dictionary<String,AnyObject>?,headerFields:Dictionary<String,AnyObject>?, progress:((progress:Float)->())?,completion:(response:AnyObject?,urlResponse:NSHTTPURLResponse?,error:NSError?)->()){}
address:String
// the request address(请求地址,是个String),
method:httpMethod
//there is a enum, specifically request method(Http请求方式,是个枚举,参考httpMethod枚举)
parameters:Dictionary<String,AnyObject>?
// this is the request parameters, when you use get method.the parameters will be added to the url, and when you use the pose method. all the parameters will be wraped in the http post content (这个就是请求的参数了,是个<String,AnyObject>?的可空字典,如果你使用Get请求方式,这些参数会以key=value的形式添加到Url后面。如果你使用Post请求,所有参数都会放在Http content包里面 )
cache:Int
//if you need cache this url, you can set the cache time bigger than 0. it any work at Get method, in post method this feature can not work (这个是设置缓存,单位是秒。如果设置的数字大于0,那么这个Url的get请求会被缓存起来,时间是你设置的秒数,参数小于 等于0无效。Post请求这个参数也无效 )
cancelToken:String?
//this is the cancel token, if you want cancel this request, just call the static funtion HttpClient.cancelRequestWithIndentity(token:string)
(这个是取消的Token,这个字符串,如果你想取消请求,只要调用这个HttpClient.cancelRequestWithIndentity(token:string)函数就行 )
queryPara:Dictionary<String,AnyObject>?
// this parameter is special. you can use it on this condition. when you use post method but also want to add some parameters to the url, then use this parameter(和parameters有点一不样,queryPara比较特别。它也是个可空的<String,AnyObject>字典,它只适合于这种场景:如果你使用Post请求,但是你也想在Url里面添加些key=value的参数,就使用这个参数 )
requestOptions:Dictionary<String,AnyObject>?
// this parameter let you personalization this request.make it not obey the global config. for instance, if you need set this request timeout . you need add timeout in the dictionary. and pass it to the request.
(requestOptions参数是你用来个性化请求用的,也是个它也是个可空的<String,AnyObject>字典。来使它不遵循全局的Http设置。比如说,你想设置该次请求的超期时间,那么你将超期时间加到字典里,再加上这个参数即可 )
headerFields:Dictionary<String,AnyObject>?
// the paramter is to set the Http request header. ( headerFields也是个可空的<String,AnyObject>字典,用来设置Http请求头)
progress:((progress:Float)->())?
// this is the upload&download progress ( progress是一个可空的block,是用来监视上传&下载进程)
completion:(response:AnyObject?,urlResponse:NSHTTPURLResponse?,error:NSError?)->())
// this is the completion call-back handler, response is a NSdata object, and you can fetch Http response info from urlResponse if error occur, the response will be nil and you can fetch the error info from error object ( completion 是一个可空的请求完成后的回调block, response实际是一个NSData对象,可以从urlResponse里获取Http response 的相关信息。如果有错误发生,那么error不为nil且response为nil,可以从error里面获取该次请求的错误,)
public static func get(address:String,parameters:Dictionary<String,AnyObject>?,cache:Int,cancelToken:String?, queryPara:Dictionary<String,AnyObject>?, completion:(response:AnyObject?,urlResponse:NSHTTPURLResponse?,error:NSError?)->())
// this is the primary get static fun,It can complete the simple basic get request.
// 这是最主要的Get静态函数,可以完成最简单基本的get请求。
HttpClient.get("http://www.baidu.com", parameters: nil, cache: 20, cancelToken: nil, completion: { (response, urlResponse, error) -> () in
if error != nil{
println("there is a error\(error)")
return
} // if error is not nil,then mean some error occur during the http request process,you must handle it.
//如果error不是nil,说明http请求过程了发生了一些错误。你必须处理它。
if let data = response as? NSData{
if let result = NSString(data: data, encoding: NSUTF8StringEncoding){
println(result)
}
}
//if error is nil, then handle the response.
//没有错误,再直接处理reponse就行
})
First: check the error parameter, if error is not nil, handle the error and display the correct message to the user
第一步:检查error参数,如果error不是nil,处理这个错误再正确地向用户展示信息。
Second: convert the response to the NSData, accord the request result, it can be a Image NSData , Text NSData or JSON.
第二步:将response转换成NSData,根据请求结果,它可能是Image的NSData,Text NSData或者JSON
Third: convert the NSData to the Model or Object and use it
第三步,将NSData转换成Model或者JSON
let path: AnyObject? = NSSearchPathForDirectoriesInDomains(NSSearchPathDirectory.DocumentDirectory, NSSearchPathDomainMask.UserDomainMask, true).first
let myPath = (path as! NSString).stringByAppendingPathComponent("img.jpg")
let httpOption = [HttpClientOption.SavePath:myPath,HttpClientOption.TimeOut:NSNumber(int: 100)]
// comstmize the Http request 个性化Http请求
let para = ["a":"123"]
HttpClientManager.Get("http://img1.gamersky.com/image2015/09/20150912ge_10/gamersky_45origin_89_201591217486B7.jpg").addParams(para).cache(100).requestOptions(httpOption).progress({ (progress) -> () in
print(progress)
}).completion({ (response, urlResponse, error) -> () in
if error != nil{
print("there is a error\(error)")
return
}
if let data = response as? NSData{
if let result = UIImage(data: data){
let tvc = ImgViewController()
tvc.img = result
self.navigationController?.pushViewController(tvc, animated: true)
}
}
})
//Unlike commom static function, use HttpClientManager functional programming style is more friendly, you do not need set unnecessary parameters to nil.just use . grammar. but if you use Objectice-C, more 【】 will mill make more improper
//不像普通的静态函数,使用HttpClientManager的函数式风格编程更友好,你不需要将不需要的参数再设置成nil了。只要用.语法就可以了,不过如果你使用Objective-C的话,太多的【】可能会看起来比较乱
cache: 20,
HttpClient可以通过URL来缓存请求,只需要将一个大于0(这是一个uint类型的秒数)传递给缓存参数(只有GET请求才会生效),HttpClient会自动缓存该请求,并将缓存内容以NSData的形式存储在APP的Cache文件夹中。如果你使用相同的URL发起另一个http请求,HttpClient会从Cache文件夹中读取数据 HttpClient可以通过URL来缓存请求,只需将一个大于0(这是一个uint类型的秒数)传递给缓存参数(只有get请求才有效果),HttpClient会自动缓存这个请求,并将数据以NSData的形式保存到APP的Cache文件夹中。如果你再次使用此URL进行请求,HttpClient会从Cache文件夹中读取数据
HttpClient.clearUrlCache("www.baidu.com") //if you can clear one specific cache, just pass the cache url
//如果你想根据Url来清空缓存,只要传Cache的url就行
HttpClient.clearCache() //call clearCache() clear all the url cache
//调用 clearCache()来清空全部缓存
不仅可以设置缓存,还可以手动清空缓存,调用静态函数clearUrlCache(url:String)并传递之前设置的缓存URL,你也可以调用静态函数clearCache()来清空HttpClient创建的所有缓存文件。 不仅设置缓存,还可以手动清空缓存,调用静态函数clearUrlCache(url:String)来传递你设置的缓存URL。同样地,你也可以调用静态函数clearCache()来清空HttpClient创建的所有缓存文件。
cancelToken: "cancel", //set the cancel token 设定取消的Token
HttpClient.cancelRequestWithIndentity("cancel") //use cancel token to cancel 传入Token来取消请求
HttpClient.cancelAllRequests() //cancel all the request 取消所有请求
在Http请求处理过程中可以取消Http请求,这是HttpClient的一个重要特性,它非常简单。当你想要取消一个请求时,你必须设置请求的Token,最好使该Token唯一。然后调用静态函数cancelRequestWithIndentity(token:String),将该Token传递给该函数,HttpClient将会取消这次请求。结果是该次请求的回调block将不会执行。同时,如果你没有设置Token,你也可以使用URL来取消请求。调用静态函数cancelRequestsWithPath(url:String)并传递URL,如果你想要取消所有请求,调用静态函数cancelAllRequests(),HttpClient将会取消所有正在处理的请求。 在Http请求处理过程中取消Http请求是HttpClient的一个主要特点,它非常简单。当你想取消一个请求时,你必须设置请求的Token,最好使其唯一。接着调用静态函数cancelRequestWithIdentity(token:String),把Token传递给该函数,HttpClient将取消这次请求。结果是该次请求的回调块将不会执行。同时,如果你没有设置Token,你也可以使用URL来取消请求。调用静态函数cancelRequestsWithPath(url:String)并根据URL取消请求。如果你想取消所有请求,调用静态函数cancelAllRequests(),HttpClient将取消所有正在处理的请求。
let myPath = "path" //declare a path, 声明一个路径
let httpOption = [HttpClientOption.SavePath:myPath,HttpClientOption.TimeOut:NSNumber(int: 100)] //declare Http request option 个性化Http请求字典
在设置好全局Http环境后,对于一些你不想遵循全局Http环境的Http请求,你可以自定义这次请求。你可以设置一些HttpClientOption,请参考HttpClientOption结构体。 在设置好全局Http环境后,有一些Http请求你并不想让它也使用全局的Http环境。你可以个性化该次请求,只要设置好HttpClientOption即可。参考HttpClientOption结构体。
一些网站需要认证,它需要你提供用户名和密码,你可以使用全局静态函数来设置全局的用户名和密码,或者将用户名和密码存储在字典中,然后传递到特定的请求中(此功能尚未测试)。 有一些网站需要认证,它需要你提供用户名和密码,你可以用全局静态函数来设置全局的用户名和密码,或者在特定的请求中加入个性化请求传递用户名和密码(该功能我没有测试)
有问题或Bug,请联系我:[email protected],我会很乐意帮您解决问题。
有任何问题或Bug请联系我 [email protected],我会很高兴为你解决问题。