.h文件
#import <Foundation/Foundation.h>
//成功的回调
typedef void(^successBlock)(id responseObj);
//失败的回调
typedef void(^failureBlock)(NSError *error);
@interface HttpGBK : NSObject<NSURLConnectionDataDelegate>
{
successBlock _saveSuccessBlock;//用于保存成功的回调
failureBlock _saveFailureBlock;//用于保存失败的回调
NSMutableData *_recevieData;//接收数据
}
+ (instancetype)shareInstance;
//自定义的POST方法
- (void)POST:(NSString *)urlString parameters:(NSDictionary *)parameters success:(successBlock)success failure:(failureBlock)failure;
@end
.m文件
#import "HttpGBK.h"
@implementation HttpGBK
+ (instancetype)shareInstance
{
static HttpGBK *manager = nil;
@synchronized(self)
{
//如果为空,则实例化
if (manager == nil)
{
manager = [[HttpGBK alloc]init];
}
}
//如果已经实例化过,直接返回
return manager;
}
//重写构造方法
- (instancetype)init
{
self = [super init];
if (self)
{
_recevieData = [[NSMutableData alloc]init];
}
return self;
}
- (void)POST:(NSString *)urlString parameters:(NSDictionary *)parameters success:(successBlock)success failure:(failureBlock)failure
{
//对数据进行备份,以防传输过程中丢失数据
_saveSuccessBlock = [success copy];
_saveFailureBlock = [failure copy];
NSStringEncoding enc = CFStringConvertEncodingToNSStringEncoding(kCFStringEncodingGB_18030_2000);
NSString *str= [self makeParameters:parameters];
//设置传输的参数为GBK
NSData *pramaData = [str dataUsingEncoding:enc];
//拼接URL
NSURL *requeturl = [NSURL URLWithString:[NSString stringWithFormat:@"%@%@",BESTURL,urlString]];
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:requeturl];
//设置为POST请求
request.HTTPMethod = @"POST";
//设置请求体
request.HTTPBody = pramaData;
NSString *charset = (__bridge NSString *)CFStringConvertEncodingToIANACharSetName(CFStringConvertNSStringEncodingToEncoding(enc));
//设置请求头
[request setValue:[NSString stringWithFormat:@"application/x-www-form-urlencoded; charset=%@", charset] forHTTPHeaderField:@"Content-Type"];
//设置请求头的长度
[request addValue:[NSString stringWithFormat:@"%ld",[pramaData length]] forHTTPHeaderField:@"Content-Length"];
//发起异步请求
[NSURLConnection connectionWithRequest:request delegate:self];
}
#pragma mark -NSURLConnectionDataDelegate
- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response
{
_recevieData.length = 0;
}
- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data
{
[_recevieData appendData:data];
}
- (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error
{
//如果有保存失败的回调才做回调.避免崩溃
if (_saveFailureBlock)
{
_saveFailureBlock(error);
}
}
-(void)connectionDidFinishLoading:(NSURLConnection *)connection
{
//成功的回调
NSStringEncoding enc = CFStringConvertEncodingToNSStringEncoding(kCFStringEncodingGB_18030_2000);
NSString *string = [[NSString alloc] initWithBytes:[_recevieData bytes] length:[_recevieData length] encoding:enc];
NSData *newData = [string dataUsingEncoding:NSUTF8StringEncoding];
id obj = [NSJSONSerialization JSONObjectWithData:newData options:NSJSONReadingMutableContainers error:nil];
if (_saveSuccessBlock)
{
//转化成功,传回字典.转化失败,把二进制数据原样传回
if (obj)
{
_saveSuccessBlock(obj);
}else
{
_saveSuccessBlock(_recevieData);
}
}
}
/**
* 接收任何证书
*
*/
- (void)connection:(NSURLConnection *)connection didReceiveAuthenticationChallenge:(NSURLAuthenticationChallenge *)challenge;
{
NSLog(@"https?");
[challenge.sender useCredential:[NSURLCredential credentialForTrust:challenge.protectionSpace.serverTrust] forAuthenticationChallenge:challenge];
}
/**
*处理SSL
*
*/
- (BOOL)connection:(NSURLConnection *)connection canAuthenticateAgainstProtectionSpace:(NSURLProtectionSpace *)protectionSpace
{
return [protectionSpace.authenticationMethod isEqualToString:NSURLAuthenticationMethodServerTrust];
}
//字典转化为字符串
-(NSString *)makeParameters:(NSDictionary *)dic
{
NSMutableArray *tempArray = [NSMutableArray array];
NSArray *keyArray = [dic allKeys];
for (NSString *key in keyArray) {
NSString *valueString = [dic objectForKey:key];
NSString *formattedString = [NSString stringWithFormat:@"%@=%@", key, valueString];
[tempArray addObject:formattedString];
}
NSString *finalString = [tempArray componentsJoinedByString:@"&"];
return finalString;
}