首先把我封裝的session請求獻上
1.BaseRequest.h
//網絡請求的基類
// POST 、 GET 、 DELETE、PUT、HEADER、TRACE、 OPTION
@interface BaseRequest : NSObject
//POST請求方法
+(void)postWithURL:(NSString *)url para:(NSDictionary *)para callBack: (void (^)(NSData* data, NSError* error))callBack;
// 提示名: (參數類型)參數名
+(void)getWithURL: (NSString *)url para:(NSDictionary *)para callBack: (void (^)(NSData* data, NSError* error))callBack;
//DELETE 類似于GET PUT類似于POST
@end
BaseRequest.m
+(void)postWithURL:(NSString *)url para:(NSDictionary *)para callBack:(void (^)(NSData *, NSError *))callBack {
//拼接url的IP位址,資源路徑、資源參數
NSMutableString *urlStr = [[NSMutableString alloc]initWithString:url];
[urlStr appendString: [self paraToString:para]];
NSURL *URL = [NSURL URLWithString:urlStr];
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:URL];
request.HTTPMethod = @"POST";
//當請求的資源參數資料過大,不能放在資源參數部分時,或者為了不暴露接口的API将相關的請求參數放到請求體中。
request.HTTPBody = [NSJSONSerialization dataWithJSONObject:para options:NSJSONWritingPrettyPrinted error:nil]; //傳回值為NSData
NSURLSession *session = [NSURLSession sharedSession];
NSURLSessionDataTask *task = [session dataTaskWithRequest:request completionHandler:^(NSData * _Nullable data, NSURLResponse * _Nullable response, NSError * _Nullable error) {
//請求響應的回調 block
if (!error) {
callBack(data,error);
// NSLog(@"%@",[[NSString alloc]initWithData:data encoding:NSUTF8StringEncoding]);
}
}];
[task resume];
}
+(void)getWithURL:(NSString *)url para:(NSDictionary *)para callBack:(void (^)(NSData *, NSError *))callBack {
//拼接url的IP位址,資源路徑、資源參數
NSMutableString *urlStr = [[NSMutableString alloc]initWithString:url];
[urlStr appendString: [self paraToString:para]];
NSURL *URL = [NSURL URLWithString:urlStr];
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:URL];
request.HTTPMethod = @"GET";
//當請求的資源參數資料過大,不能放在資源參數部分時,或者為了不暴露接口的API将相關的請求參數放到請求體中。
request.HTTPBody = [NSJSONSerialization dataWithJSONObject:para options:NSJSONWritingPrettyPrinted error:nil]; //傳回值為NSData
NSURLSession *session = [NSURLSession sharedSession];
NSURLSessionDataTask *task = [session dataTaskWithRequest:request completionHandler:^(NSData * _Nullable data, NSURLResponse * _Nullable response, NSError * _Nullable error) {
//請求響應的回調 block
if (!error) {
callBack(data,error);
// NSLog(@"%@",[[NSString alloc]initWithData:data encoding:NSUTF8StringEncoding]);
}
}];
[task resume];
}
//将para字典拼接為資源參數部分
+(NSString *)paraToString: (NSDictionary *)para {
NSMutableString *str = [NSMutableString stringWithString:@"?"];
for (NSString *key in para.allKeys) {
[str appendFormat:@"%@=%@&",key,para[key]];
}
if ([str hasSuffix:@"&"]){
//删除多餘的& 連接配接符
[str deleteCharactersInRange:NSMakeRange(str.length - , )];
}
//如果資源中含有中文或其他等特殊字元時進行Unicode編碼
NSString *paraStr = [str stringByAddingPercentEncodingWithAllowedCharacters:[NSCharacterSet URLFragmentAllowedCharacterSet]];
return paraStr;
}
@end
![](https://img.laitimes.com/img/9ZDMuAjOiMmIsIjOiQnIsICdzFWRoRXdvN1LclHdpZXYyd2LcBzNvwVZ2x2bzNXak9CX90TQNNkRrFlQKBTSvwFbslmZvwFMwQzLcVmepNHdu9mZvwFVywUNMZTY18CX052bm9CX9UFVOdXUE50MJpXTmZEWjZXUYpVd1kmYr50MZV3YyI2cKJDT29GRjBjUIF2LcRHelR3LcJzLctmch1mclRXY39TNzMDNxkTN2EzMxEDM3EDMy8CX0Vmbu4GZzNmLn9Gbi1yZtl2Lc9CX6MHc0RHaiojIsJye.jpg)
str的列印結果 是這樣,并經過json轉化
{
“result”: {
“areaid”: “410611”,
“email”: “[email protected]”,
“id”: 35,
“loginflag”: “1”,
“mobile”: “”,
“name”: “互動體驗中心”,
“phone”: “”,
“photo”: “http://biot.365960.cn/image/user/35/1483577527069.png“,
“remarks”: “”,
“roleid”: “9”,
“usertype”: “2”
},
“code”: 0,
“message”: “登入成功”,
“error”: false
}
列印的經過NSJSONSerialization 解析的 為 NSDictionary對象類型
{
code = 0;
error = 0;
message = “\U767b\U5f55\U6210\U529f”;
result = {
areaid = 410611;
email = “[email protected]”;
id = 35;
loginflag = 1;
mobile = “”;
name = “\U4e92\U52a8\U4f53\U9a8c\U4e2d\U5fc3”;
phone = “”;
photo = “http://biot.365960.cn/image/user/35/1483577527069.png“;
remarks = “”;
roleid = 9;
usertype = 2;
};
}
不同之處在于 後者的非數字型鍵值沒有雙引号,不能進行json轉化
通過AFN來擷取資料
在這裡我們列印的 AFN傳回的資料responseObject,列印結果
{
code = 0;
error = 0;
message = “\U767b\U5f55\U6210\U529f”;
result = {
areaid = 410611;
email = “[email protected]”;
id = 35;
loginflag = 1;
mobile = “”;
name = “\U4e92\U52a8\U4f53\U9a8c\U4e2d\U5fc3”;
phone = “”;
photo = “http://biot.365960.cn/image/user/35/1483577527069.png“;
remarks = “”;
roleid = 9;
usertype = 2;
};
}
那麼這邊同上邊列印NSDictionary的結果,是以
AFN網絡請求方法中傳回的responseObject 為 已經轉化成為NSDictionary 或 NSArray的對象, 省了 一步将請求下來的data轉化為NSDictionary 或 NSArray!