iOS网络请求简单封装

用惯了AFNetWorking和ASI,也想尝试自己写一个

: NSObject+ (void)POSTParameters:(NSDictionary *)parameters method:(NSString *)method success:(void (^)(NSDictionary *dic))success animation:(BOOL)animation;@end+ (void)POSTParameters:(NSDictionary *)parameters method:(NSString *)method success:(void (^)(NSDictionary *dic))success animation:(BOOL)animation{if (animation == YES) {MBProgressHUD *hud = [MBProgressHUD showHUDAddedTo:[UIApplication sharedApplication].keyWindow animated:YES];hud.labelText = @”加载中…”;}NSMutableURLRequest* urlRequest = [[NSMutableURLRequest alloc] initWithURL:[NSURL URLWithString:[NSString stringWithFormat:@”%@%@”,BASEURL,method]]];[urlRequest setHTTPMethod:@”POST”];if (parameters.allKeys) {NSString *postStr = @””;for (NSString *key in parameters.allKeys) {NSString *value = [parameters valueForKey:key];if (postStr.length == 0) {postStr = [NSString stringWithFormat:@”%@=%@”,key,value];}else{postStr = [postStr stringByAppendingString:[NSString stringWithFormat:@”&%@=%@”,key,value]];}}NSData *postData = [postStr dataUsingEncoding:NSUTF8StringEncoding];[urlRequest setHTTPBody:postData];}[NSURLConnection sendAsynchronousRequest:urlRequestqueue:[NSOperationQueue mainQueue]completionHandler:^(NSURLResponse *response, NSData *data, NSError *error){[MBProgressHUD hideAllHUDsForView:[UIApplication sharedApplication].keyWindow animated:YES];NSString *responseString = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];NSString *jsonStr = [self flattenHTML:responseString];NSDictionary *dic = [NSJSONSerialization JSONObjectWithData:[jsonStr dataUsingEncoding:NSUTF8StringEncoding] options:NSJSONReadingMutableContainers error:nil];success(dic);}];}//过滤HTML标签+ (NSString *)flattenHTML:(NSString *)html {NSScanner *theScanner;NSString *text = nil;theScanner = [NSScanner scannerWithString:html];while ([theScanner isAtEnd] == NO) {[theScanner scanUpToString:@”<” intoString:NULL] ;[theScanner scanUpToString:@”>” intoString:&text] ;html = [html stringByReplacingOccurrencesOfString:[NSString stringWithFormat:@”%@>”, text]withString:@””];}return html;}@end

调用非常简单

1.首先到LYNetWorking.h中配置一下你的BASEURL

2.调用POSTParameters方法,method参数是你url的后缀。animation:YES代表使用加载动画。

3.回调NSDictionary *dic,返回的数据已经解析成一个字典了,并且过滤掉XML标签

#import “LYNetWorking.h”[LYNetWorking POSTParameters:@{@”userName”:@”用这里写代码片户名”,@”password”:@”12345″} method:@”OnRegister” success:^(NSDictionary *dic) {} animation:YES];

,你不勇敢,没人替你坚强。

iOS网络请求简单封装

相关文章:

你感兴趣的文章:

标签云: