这是 Swift3.0 版的 直接建一个 Swift 文件粘贴代码就可以使用了
class BaseRequest{
class func getWithURL(_ url:String!,para:NSDictionary?,callBack:@escaping (_ data:Data?,_ error:NSError?)->Void)->Void
{
let session = URLSession.shared
let urlStr = NSMutableString.init(string: url)
if para != nil {
urlStr.append(self.encodeUniCode(self.parasToString(para!) as NSString) as String)
}
var request = URLRequest.init(url: (URL.init(string: urlStr as String))!)
request.httpMethod = "GET"
let dataTask = session.dataTask(with: request, completionHandler: { (data, response, error) in
//let res:NSHTTPURLResponse = response as! NSHTTPURLResponse
if data != nil
{
callBack(data,nil)
}else
{
callBack(nil,(error as? NSError?)!)
}
})
//启动请求任务
dataTask .resume()
}
class func postWithURL(_ url:String!,para:NSDictionary?,callBack:@escaping (_ data:Data?,_ error:NSError?)->Void)->Void{
let session = URLSession.shared
let urlStr = NSMutableString.init(string: url)
if para != nil {
urlStr.append(self.encodeUniCode(self.parasToString(para!) as NSString) as String)
}
var request = URLRequest.init(url: (URL.init(string: urlStr as String))!)
request.httpMethod = "POST"
let dataTask = session.dataTask(with: request) { (data, response, error) in
if error == nil
{
callBack(data,nil)
}else
{
callBack(nil,error as NSError?)
}
}
//session.dataTask(with: request, completionHandler: { (data, response, error) in
//}
//启动请求任务
dataTask .resume()
}
class func parasToString(_ para:NSDictionary?)->String
{
let paraStr = NSMutableString.init(string: "?")
for (key,value) in para as! [String :String]
{
paraStr.appendFormat("%@=%@&", key,value)
}
if paraStr.hasSuffix("&"){
paraStr.deleteCharacters(in: NSMakeRange(paraStr.length - 1, 1))
}
//将URL中的特殊字符进行转吗
// paraStr.stringByAddingPercentEncodingWithAllowedCharacters(NSCharacterSet.URLFragmentAllowedCharacterSet())
//移除转码
// paraStr.stringByRemovingPercentEncoding
return String(paraStr)
}
class func encodeUniCode(_ string:NSString)->NSString
{
return string.addingPercentEncoding(withAllowedCharacters: CharacterSet.urlFragmentAllowed)! as NSString
}
}
这是 OC 版的
BaseRequest.h 文件
#import <Foundation/Foundation.h>
@interface BaseRequest : NSObject
//一个请求: 1.IP地址 2. 资源路径 资源参数(para) 3.回调(返回数据)
// GET 请求方式
+ (void)getWithURL:(NSString *)url para:(NSDictionary *)para callBack:(void(^)(NSData * data, NSError * error))callBack;
// POST 请求方式
+ (void)postWithURL:(NSString *)url para:(NSDictionary *)para callBack:(void(^)(NSData * data, NSError * error))callBack;
@end
BaseRequest.m 文件
#import "BaseRequest.h"
@implementation BaseRequest
+(void)getWithURL:(NSString *)url para:(NSDictionary *)para callBack:(void (^)(NSData *, NSError *))callBack{
//处理url 和 para 的拼接
NSMutableString * urlStr = [[NSMutableString alloc]initWithString:url];
// 拼接资源参数部分
[urlStr appendString:[self paraToString:para]];
NSURL * URL = [NSURL URLWithString:urlStr];
// 创建请求对象
NSMutableURLRequest * request = [NSMutableURLRequest requestWithURL:URL];
request.timeoutInterval = 20;
request.HTTPMethod = @"GET";
// 创建session
NSURLSession * session = [NSURLSession sharedSession];
// 创建task
NSURLSessionDataTask * task = [session dataTaskWithRequest:request completionHandler:^(NSData * _Nullable data, NSURLResponse * _Nullable response, NSError * _Nullable error) {
// 请求结束以后的回调block
callBack(data,error);
}];
// 启动任务
[task resume];
}
+(void)postWithURL:(NSString *)url para:(NSDictionary *)para callBack:(void (^)(NSData *, NSError *))callBack{
//处理url 和 para 的拼接
NSMutableString * urlStr = [[NSMutableString alloc]initWithString:url];
// 拼接资源参数部分
[urlStr appendString:[self paraToString:para]];
NSURL * URL = [NSURL URLWithString:urlStr];
// 创建请求对象
NSMutableURLRequest * request = [NSMutableURLRequest requestWithURL:URL];
request.timeoutInterval = 20;
request.HTTPMethod = @"POST";
// 创建session
NSURLSession * session = [NSURLSession sharedSession];
// 创建task
NSURLSessionDataTask * task = [session dataTaskWithRequest:request completionHandler:^(NSData * _Nullable data, NSURLResponse * _Nullable response, NSError * _Nullable error) {
// 请求结束以后的回调block
callBack(data,error);
}];
// 启动任务
[task resume];
}
// 将para 拼接成 key1=value1&key2=value2&...的形式
+ (NSString *)paraToString:(NSDictionary *)para{
NSMutableString * paraStr = [[NSMutableString alloc]initWithString:@"?"];// 资源参数部分以 ? 开头
if (para && para.allKeys.count > 0) { // 字典不为nil, 且有键值对才进行拼接
for (NSString * key in para.allKeys) {
[paraStr appendFormat:@"%@=%@&",key,para[key]]; // 拼接键值对
}
}
// 如果有多余的连接符& 要删除
if ([paraStr hasSuffix:@"&"]) {
// 删除字符串最后一个字符
[paraStr deleteCharactersInRange:NSMakeRange(paraStr.length - 1, 1)];
}
// 如果参数中有中文或 "{" "}" "*" 等特殊字符时,应该进行Unicode编码,否则请求会得不到数据
NSString * pStr = [paraStr stringByAddingPercentEncodingWithAllowedCharacters:[NSCharacterSet URLFragmentAllowedCharacterSet]];
// 解码
// [pStr stringByRemovingPercentEncoding];
return pStr;
}
@end