IOS使用AFN框架傳送POST/GET請求
阿新 • • 發佈:2018-11-02
1. 利用第三方框架獲取伺服器資料(AFNetworking框架);
* 2.使用POST/GET方式進行提交*
3.頭部檔案匯入AFNetworking.h
一:首先看程式碼POST請求
//請求的引數
NSDictionary *parameters = @{@"username":username,
@"password":password
};
//請求的url
NSString *urlString = @"http://......../ErpProject/user/getUser" ;
//請求的managers
AFHTTPSessionManager *managers = [AFHTTPSessionManager manager];
managers.requestSerializer=[AFJSONRequestSerializer serializer];
//managers.responseSerializer=[AFJSONResponseSerializer serializer];
managers.responseSerializer.acceptableContentTypes = [NSSet setWithObjects:@"text/html" ,@"text/plain",@"application/json",@"text/javascript", nil];
[managers POST:urlString parameters:parameters progress:^(NSProgress * _Nonnull uploadProgress) {
} success:^(NSURLSessionDataTask * _Nonnull task, id _Nullable responseObject) {
NSLog(@"請求成功,伺服器返回的資訊%@",responseObject);
} failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
NSLog(@"請求失敗,伺服器返回的錯誤資訊%@",error);
}];
二:其次看使用GET方式請求
NSDictionary *dict = @{
@"id":@"inedex_id",
};
AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
[manager GET:@"http://indexen/cn/com?" parameters:dict progress:nil success:
^(NSURLSessionDataTask * _Nonnull task, id _Nullable responseObject) {
NSLog(@"請求成功---%@",responseObject);
} failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
NSLog(@"請求失敗,伺服器返回的錯誤資訊%@",error);
}];
三:該注意的細節:
AFHTTPSessionManager *managers = [AFHTTPSessionManager manager];
managers.requestSerializer=[AFHTTPRequestSerializer serializer];
managers.responseSerializer=[AFHTTPResponseSerializer serializer];
或者:
AFHTTPSessionManager *managers = [AFHTTPSessionManager manager];
managers.requestSerializer=[AFJSONRequestSerializer serializer];
//managers.responseSerializer=[AFJSONResponseSerializer serializer];
四:轉換為字典(有些服務端資料需要轉換才可以讀區到):
NSDictionary *dic = [NSJSONSerialization JSONObjectWithData:responseObject options:NSJSONReadingMutableContainers error:nil];
五:AFNetworking基本的功能,請求網路資料,就到這裡了,如果滿意可以給予點贊或者關注,後續還會繼續釋出更完美的文章,如果有不足之處,可以提出來共同努力!謝謝!