// h 里面写的
#import <Foundation/Foundation.h>
typedef void(^Myblock)(id object);
@interface NetworkHandle : NSObject
+ (void)getDataWithURLString:(NSString *)string compare:(Myblock)block;
+ (void)postDataWithURLString:(NSString *)string
andBodyString:(NSString *)bodyString
compare:(Myblock)block;
@end
//m里面写的
#import "NetworkHandle.h"
@interface NetworkHandle ()
@property (nonatomic, strong) NSMutableData *data;
@end
@implementation NetworkHandle
+ (void)getDataWithURLString:(NSString *)string compare:(Myblock)block{
//对地址做一次UTF-8的转码,防止参数里面有中文
NSString *urlStr = [string stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
//将地址转换成url格式
NSURL *url = [NSURL URLWithString:urlStr];
//设置请求方式
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];
[request setHTTPMethod:@"GET"];
//同步还是异步
[NSURLConnection sendAsynchronousRequest:request queue:[NSOperationQueue mainQueue] completionHandler:^(NSURLResponse *response, NSData *data, NSError *connectionError) {
if (data != nil) {
//因为不确定数据的类型,所以用id泛型指针去接收
id object = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingAllowFragments error:nil];
block(object);
}
}];
}
+ (void)postDataWithURLString:(NSString *)string andBodyString:(NSString *)bodyString compare:(Myblock)block{
NSString *urlStr = [string stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
NSURL *url = [NSURL URLWithString:urlStr];
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];
NSString *parStr = bodyString;
NSData *patData = [parStr dataUsingEncoding:NSUTF8StringEncoding];
[request setHTTPMethod:@"POST"];
[request setHTTPBody:patData];
[NSURLConnection sendAsynchronousRequest:request queue:[NSOperationQueue mainQueue] completionHandler:^(NSURLResponse *response, NSData *data, NSError *connectionError) {
if (data != nil) {
id object = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingAllowFragments error:nil];
block(object);
}
}];
}