您的位置:首页 > 理论基础 > 计算机网络

iOS网络请求简单封装

2015-06-30 21:42 477 查看
用惯了AFNetWorking和ASI,也想尝试自己写一个

#import <Foundation/Foundation.h>
#import "MBProgressHUD.h"
#define BASEURL @"http://140.207.46.14:8017/UserInfoWebService.asmx/"
@interface LYNetWorking : NSObject
+ (void)POSTParameters:(NSDictionary *)parameters method:(NSString *)method success:(void (^)(NSDictionary *dic))success animation:(BOOL)animation;
@end


#import "LYNetWorking.h"

@implementation LYNetWorking

+ (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:urlRequest
queue:[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];
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: