有改动
HttpUtil.h
#import <Foundation/Foundation.h>
#import <UIKit/UIKit.h>
#import "Reachability.h"
@interface HttpUtil : NSObject
+ (BOOL)NetWorkIsOK;//检查网络是否可用
+ (void)post:(NSString *)Url RequestParams:(NSDictionary *)params FinishBlock:(void (^)(NSURLResponse *response, NSData *data, NSError *connectionError)) block;//post请求封装
@end
HttpUtil.m
#import "HttpUtil.h"
@implementation HttpUtil
+ (BOOL)NetWorkIsOK{
//检查网络是否可用
if(
([[Reachability reachabilityForInternetConnection] currentReachabilityStatus]
!= NotReachable)
&&
([[Reachability reachabilityForLocalWiFi] currentReachabilityStatus]
!= NotReachable)
){
return YES;
}else{
return NO;
}
}
+ (void)post:(NSString *)Url RequestParams:(NSDictionary *)params FinishBlock:(void (^)(NSURLResponse *response, NSData *data, NSError *connectionError)) block{
//post请求封装
//把传进来的URL字符串转变为URL地址
NSURL *url = [NSURL URLWithString:Url];
//请求初始化,可以在这针对缓存,超时做出一些设置
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url
cachePolicy:NSURLRequestReloadIgnoringCacheData
timeoutInterval:20];
//解析请求参数,用NSDictionary来存参数,通过自定义的函数parseParams把它解析成一个post格式的字符串
NSString *parseParamsResult = [self parseParams:params];
NSData *postData = [parseParamsResult dataUsingEncoding:NSUTF8StringEncoding];
[request setHTTPMethod:@"POST"];
[request setHTTPBody:postData];
//创建一个新的队列(开启新线程)
NSOperationQueue *queue = [NSOperationQueue new];
//发送异步请求,请求完以后返回的数据,通过completionHandler参数来调用
[NSURLConnection sendAsynchronousRequest:request
queue:queue
completionHandler:block];
// return result;
}
//把NSDictionary解析成post格式的NSString字符串
+ (NSString *)parseParams:(NSDictionary *)params{
NSString *keyValueFormat;
NSMutableString *result = [NSMutableString new];
//实例化一个key枚举器用来存放dictionary的key
NSEnumerator *keyEnum = [params keyEnumerator];
id key;
while (key = [keyEnum nextObject]) {
keyValueFormat = [NSString stringWithFormat:@"%@=%@&",key,[params valueForKey:key]];
[result appendString:keyValueFormat];
NSLog(@"post()方法参数解析结果:%@",result);
}
return result;
}
@end
调用演示如下
if([HttpUtil NetWorkIsOK]){
//发送请求,并且得到返回的数据
//ValueUtil是我保存接口URL的类
[HttpUtil post:[ValueUtil getLoginURL] RequestParams:params FinishBlock:^(NSURLResponse *response, NSData *data, NSError *connectionError) {
//传回来的数据存在,则执行该回调函数
if(data){
//子线程通知主线程更新UI,selector中是要执行的函数,data是传给这个函数的参数
//login_callBack就处理返回来的消息,这里就简单的输出,登录成功
[self performSelectorOnMainThread:@selector(login_callBack:) withObject:data waitUntilDone:YES];
}else{
NSLog(@"无效的数据");
}
}];
}
- (void)login_callBack:(id)value{
NSLog(@"登录成功");
NSData *data = (NSData *)value;
NSString *result = [[NSString alloc]initWithData:data encoding:NSUTF8StringEncoding];
NSLog(result);
}