http请求
ios10之后访问http请求需要在info.plist中加入字段
image<key>NSAppTransportSecurity</key>
<dict>
<key>NSAllowsArbitraryLoads</key>
<true/>
</dict>
AFNetworking结构分析
- NSURLConnection
- AFURLConnection0peration
- AFHTTPRequestOperationManager
- AFHTTPRequest0peration
新版本中已经废除
- NSURLsession
-
AFURLSessionManager
-
AFHTTPSessionManager
- Reachability:网络状态相关接口
- AFNetworkReachabilityManager
- Security:安全性相关的操作接口
- AFSecurityPolicy
- Serialization:解析数据相关的操作
• AFURLRequestSerialization
• AFURLResponseSerialization
- UIKit:UI界面相关接口
- UIActivityIndicatorView+AFNetworking
- UIAlertView+AFNetworking
- UIButton+AFNetworking
- UIImageView+AFNetworking
- UIKit+AFNetworking
- UiprogressView+AFNetwo rking
- UIRefreshControl+AFNetworking
- UIWebView+AFNetworking
核心模块
imageAFHTTPSessionManager是继承于AFURLSessionManager的,我们一般做网络请求都是用这个类,但是它本身是没有做实事的,只是做了一些简单的封装,把请求逻辑分发给父类AFURLSessionManager或者其它类去做。
AFHTTPSessionManager
Get请求
+(void)getJokeBySort:(NSString *)sort
page:(int)page
pageSize:(int)size
time:(NSString *)time
key:(NSString *)key
success:(void (^)( NSDictionary *resultDic))success
failure:(void (^)( NSError *error))failure{
AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
/*
requestSerializer 上传的参数是什么格式的
AFHTTPRequestSerializer 普通的http的编码格式,二进制 sort=sort&page=page,默认
AFJSONRequestSerializerjson 编码格式 "{"sort":"sort","page":"page"}"
AFPropertyListRequestSerializerplist 编码格式
*/
manager.requestSerializer = [AFHTTPRequestSerializer serializer];
/*
请求超时设置
*/
manager.requestSerializer.timeoutInterval = 20.f;
/*
[AFHTTPResponseSerializer serializer]; 直接使用“服务器本来返回的数据”,不做任何解析
[AFJSONResponseSerializer serializer]; 解析服务器数据,返回的是JSON数据,默认的
[AFXMLParserResponseSerializer serializer]; 解析服务器数据,返回的XML数据
*/
manager.responseSerializer = [AFHTTPResponseSerializer serializer];
/*
如果想在header里加东西的话token/User-Agent/Content-Type
[manager.requestSerializer setValue:token forHTTPHeaderField:@"token"];
*/
NSDictionary *para = @{
@"sort":sort,
@"page":[NSNumber numberWithInt:page],
@"pageSize":[NSNumber numberWithInt:size],
@"time":time,
@"key":key
};
NSString *url =@"http://v.juhe.cn/joke/content/list.php";
[manager GET:url parameters:para progress:^(NSProgress * _Nonnull downloadProgress) {
} success:^(NSURLSessionDataTask * _Nonnull task, id _Nullable responseObject) {
NSLog(@"----%@",responseObject);
} failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
NSString *domin = error.domain;
NSLog(@"+++++%@",domin);
}];
}
-(void)getJoke{
[DataManager getJokeBySort:@"desc" page:1 pageSize:10 time:@"1583980251" key:@"640c0f7e1927dc42ca137858a54ed935" success:^(NSDictionary * _Nonnull resultDic) {
} failure:^(NSError * _Nonnull error) {
}];
}
Post请求(x-www-form-urlencoded)
+(void)loginUserName:(NSString *)userName
passWord:(NSString *)password
Success:(void (^)( NSDictionary *resultDic))success
failure:(void (^)( NSError* error))failure{
AFHTTPSessionManager *sessionManager = [AFHTTPSessionManager manager];
sessionManager.requestSerializer = [AFHTTPRequestSerializer serializer];
sessionManager.responseSerializer = [AFHTTPResponseSerializer serializer];
sessionManager.requestSerializer.timeoutInterval = 20;
//如果报接受类型(Cntent-Type)不一致请替换text/html
sessionManager.responseSerializer.acceptableContentTypes = [NSSet setWithObject:@"text/html"];
NSString *urlString = @"http://43.248.49.207:7001/HGAuth/api/auth/login";
NSDictionary*parma=@{@"action":@"DO",@"hgflag":userName,@"password":@"96E79218965EB72C92A549DD5A330112"};
/*
默认的Content-Type为application/x-www-form-urlencoded,且body中没有参数
*/
[sessionManager POST:urlString parameters:parma progress:^(NSProgress * _Nonnull uploadProgress) {
} success:^(NSURLSessionDataTask * _Nonnull task, id _Nullable responseObject) {
id result = [NSJSONSerialization JSONObjectWithData:responseObject options:(NSJSONReadingMutableContainers) error:nil];
NSLog(@"---%@",responseObject);
} failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
NSLog(@"===%@",error.domain);
}];
}
-(void)postLogin{
[DataManager loginUserName:@"lt\\jinguanyd6" passWord:@"111111" Success:^(NSDictionary * _Nonnull resultDic) {
} failure:^(NSError * _Nonnull error) {
}];
}
post请求(form-data形式需要上传文件)
+ (void)postImageSuccess:(void(^)(void))success
failure:(void(^)(NSError *error))failure{
AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
manager.requestSerializer = [AFHTTPRequestSerializer serializer];
manager.responseSerializer = [AFHTTPResponseSerializer serializer];
NSString *urlString = @"http://43.248.49.207:8080/HGMMS/appInterface/sendFeedbackImg.html";
[manager POST:urlString parameters:nil constructingBodyWithBlock:^(id<AFMultipartFormData> _Nonnull formData) {
UIImage *image = [UIImage imageNamed:@"iceImage"];
NSData *imageData = UIImageJPEGRepresentation(image,0.2);
[formData appendPartWithFormData:[@"611" dataUsingEncoding:NSUTF8StringEncoding] name:@"feedbackId"];
/*
*该方法的参数
1\. appendPartWithFileData:要上传的照片[二进制流]
2\. name:对应网站上[upload.php中]处理文件的字段(比如upload)
3\. fileName:要保存在服务器上的文件名
4\. mimeType:上传的文件的类型
*/
[formData appendPartWithFileData:imageData name:@"file" fileName:@"file.jpg" mimeType:@"image/jpeg"];
} progress:^(NSProgress * _Nonnull uploadProgress) {
} success:^(NSURLSessionDataTask * _Nonnull task, id _Nullable responseObject) {
NSLog(@"---------%@",responseObject);
} failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
NSLog(@"++++++++%@",error.domain);
}];
}
AFURLSessionManager
post请求body中有参数,可配置Content-type
/*
post,body中有参数
*/
+(void)cheakNewVisionSuccess:(void (^)( NSDictionary *resultDic))success
failure:(void (^)( NSError *error))failure{
AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
manager.responseSerializer = [AFHTTPResponseSerializer serializer];
NSString *URLString = @"http://43.248.49.207:8080/HGMMS/appInterface/checkPortalVersionCdn.html";
NSURL *url = [NSURL URLWithString:URLString];
NSURLRequest *request = [NSURLRequest requestWithURL:url];
NSError *serializationError = nil;
NSMutableURLRequest *mutaRequest = [[manager.requestSerializer requestBySerializingRequest:request withParameters:nil error:&serializationError] mutableCopy];
mutaRequest.HTTPMethod = @"POST";
if (serializationError) {
if (failure) {
dispatch_async(manager.completionQueue ?: dispatch_get_main_queue(), ^{
failure( serializationError);
});
}
return;
}
//设置Content-type为text/html; charset=utf-8,对应postman-body-raw-text/html
[mutaRequest addValue: @"text/html; charset=utf-8" forHTTPHeaderField:@"Content-Type"];
//添加body
NSString*body=@"{\"os\":\"2\"}";
[mutaRequest setHTTPBody:[body dataUsingEncoding:NSUTF8StringEncoding]];
__block NSURLSessionDataTask *dataTask = nil;
dataTask = [manager dataTaskWithRequest:mutaRequest uploadProgress:^(NSProgress * _Nonnull uploadProgress) {
} downloadProgress:^(NSProgress * _Nonnull downloadProgress) {
} completionHandler:^(NSURLResponse * _Nonnull response, id _Nullable responseObject, NSError * _Nullable error) {
if (error) {
if (failure) {
failure(error);
}
} else {
if (success) {
success(responseObject);
}
}
}];
[dataTask resume];
}
Content-Type
Content-Type代表发送端(客户端|服务器)发送的实体数据的数据类型。
比如:Content-Type:text/html;
代表发送端发送的数据格式是html
-
常见的媒体格式类型如下:
text/html : HTML格式
text/plain :纯文本格式
text/xml : XML格式
image/gif :gif图片格式
image/jpeg :jpg图片格式
image/png:png图片格式 -
以application开头的媒体格式类型:
application/xhtml+xml :XHTML格式
application/xml : XML数据格式
application/atom+xml :Atom XML聚合格式
application/json : JSON数据格式
application/pdf :pdf格式
application/msword : Word文档格式
application/octet-stream : 二进制流数据(如常见的文件下载)
application/x-www-form-urlencoded : <form encType=””>中默认的encType,form表单数据被编码为key/value格式发送到服务器(表单默认的提交数据的格式) -
以audio开头的常见媒体格式文件:
'audio/x-wav' : wav文件
'audio/x-ms-wma' : wma 文件
'audio/mp3' : mp3文件 -
以video开头的常见媒体格式文件:
'video/x-ms-wmv' : wmv文件
'video/mpeg4' : mp4文件
'video/avi' : avi文件 -
另外一种常见的媒体格式是上传文件之时使用的:
multipart/form-data : 需要在表单中进行文件上传时,就需要使用该格式
Content-Type 被指定为 application/x-www-form-urlencoded;例如 JQuery 和 QWrap 的 Ajax,Content-Type 默认值都是「application/x-www-form-urlencoded;charset=utf-8」
网友评论