ASIHTTPRequest作爲一個比較知名的http訪問庫本身功能比較強大,在項目開發過程中,如果每個請求,都要使用ASIHTTPRequest來寫,有以下幾個弊端:
(1)繁瑣,無封裝性。
(2)如果直接Synchronous方法,阻塞UI,而使用異步的Asynchronous,則要寫很多委託,也是非常的麻煩.
(3)http請求基本上是給一個請求,返回一個請求結果,直接使用ASIHTTPRequest還無法做到,所以需要有一個比較好的封裝。
基於以上的三個原因,做了一個封裝
(1)頭文件
//
// MyHttpRequest.h
// djy
//
// Created by SuFuTe on 14/12/31.
// Copyright (c) 2014年 SuFuTe. All rights reserved.
//
/**
封裝網絡請求類(只支持POST)
*/
#import <Foundation/Foundation.h>
#import "ASIFormDataRequest.h"
typedef void (^FinishBlock)(NSDictionary *responseResult);
@interface MyHttpRequest : NSObject<ASIHTTPRequestDelegate>
//@property (strong, nonatomic) FinishBlock finishBlock;
//@property(nonatomic,strong) ASIFormDataRequest *asiRequest;
//+ (MyHttpRequest *)sharedMyHttpRequest;
/**
參數:1.地址url 2.Request header 沒有時傳nil 3.body參數
*/
+ (void)postRequestWithURL:(NSString *)urlStr withHeader:(NSMutableDictionary *)header paramters:(NSDictionary *)paramters finishBlock:(FinishBlock)block;
@end
(2)實現文件
//
// MyHttpRequest.m
// djy
//
// Created by SuFuTe on 14/12/31.
// Copyright (c) 2014年 SuFuTe. All rights reserved.
//
#import "MyHttpRequest.h"
//static MyHttpRequest *_myhttpRequest;
@implementation MyHttpRequest
//+(id)allocWithZone:(struct _NSZone *)zone
//{
// @synchronized(self){
// if (!_myhttpRequest) {
// _myhttpRequest = [super allocWithZone:zone];
// }
// }
//
// return _myhttpRequest;
//
//}
//
//
//+ (MyHttpRequest *)sharedMyHttpRequest
//{
// @synchronized(self){
// if (!_myhttpRequest) {
// _myhttpRequest = [[super alloc] init];
// }
// }
// return _myhttpRequest;
//}
+ (void)postRequestWithURL:(NSString *)urlStr withHeader:(NSMutableDictionary *)header paramters:(NSDictionary *)paramters finishBlock:(FinishBlock)block
{
if (paramters.count == 0||paramters == nil) {
return;
}else{
NSURL *url = [NSURL URLWithString:urlStr];
ASIFormDataRequest *asiRequest = [ASIFormDataRequest requestWithURL:url];
__block ASIFormDataRequest *brRequest = asiRequest;
for(NSString *key in paramters){
[asiRequest setPostValue:paramters[key] forKey:key];
}
if (header != nil) {
[asiRequest setRequestHeaders:header];
}
[asiRequest setRequestMethod:@"POST"];
[asiRequest setDelegate:self];
[asiRequest setCompletionBlock:^{
NSData *data =[brRequest responseData];
NSDictionary *dictionary = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingAllowFragments error:nil];
block(dictionary);
}];
[asiRequest setFailedBlock:^{
NSLog(@"%i",[brRequest responseStatusCode]);
NSLog(@"%@",[brRequest responseString]);
block(nil);
}];
[asiRequest startAsynchronous];
}
}
@end
[MyHttpRequest postRequestWithURL:@"http://test.pbofans.com:70/autobot/app/s/login" withHeader:nil paramters:@{@"username":@"13812186059",@"password":[NSString stringWithFormat:@"%@",[self sha256HashFor:@"123456"]]} finishBlock:^(NSDictionary *responseResult){
}];