ASIFormDataRequest /AFNetworking GET/POST請求的簡單封裝(block)

一 :普通請求,根據設置參數andRequestType爲POST或GET 來確定請求方式

ASIFormDataRequest部分:

DataRequest.h文件

//  Copyright (c) 2013年 dong. All rights reserved.
//
#import <Foundation/Foundation.h>
@interface DataRequest : NSObject
+(void)dataWithDic :(NSMutableDictionary *)dic andRequestType:(NSString *)requestType andRequestCollectionAddressType:(NSString *)collectionAddressType andRequestSearchType:(NSString *)searchType andBlock:(void(^)(NSString *requestStr))block;
+(NSMutableDictionary *)jsonValue :(NSString *)str;
@end


DataRequest.m 文件

//  Copyright (c) 2013年 dong. All rights reserved.
//
//add into  .pch  這裏是隨便寫的請求地址,
#define WEBSERVER @"https://www.google.com."

#import "DataRequest.h"
#import "ASIFormDataRequest.h"
@implementation DataRequest
+(void)dataWithDic:(NSMutableDictionary *)dic andRequestType:(NSString *)requestType andRequestCollectionAddressType:(NSString *)collectionAddressType andRequestSearchType:(NSString *)searchType andBlock:(void (^)(NSString *))block{
    
    NSString *httpStr=[NSString stringWithFormat:@"%@%@/%@",WEBSERVER,collectionAddressType,searchType];
    NSURL *url = [NSURL URLWithString:httpStr];
    ASIFormDataRequest * request;
    
    if ([requestType isEqualToString:@"POST"]){
        
        request=[ASIFormDataRequest requestWithURL:url];
        for (NSString *key in [dic allKeys]) {
            NSString *value=[dic objectForKey:key];
            [request setPostValue:value forKey:key];
        }
    }
    if ([requestType isEqualToString:@"GET"]){
        
        //遍歷 轉換正確的GET請求方式
        int urlCount=1;
        NSString *getUrl=[httpStr stringByAppendingString:@"?"];
        for (NSString *key in [dic allKeys]) {
            NSString *value=[dic objectForKey:key];
            if (urlCount==[[dic allKeys] count]) {
                getUrl=[getUrl stringByAppendingString:[NSString stringWithFormat:@"%@=%@",key,value]];
            }else{
                getUrl=[getUrl stringByAppendingString:[NSString stringWithFormat:@"%@=%@&",key,value]];
            }
            urlCount++;
        }
        request=[[ASIFormDataRequest alloc] initWithURL:[NSURL URLWithString:getUrl]];
    }
    
    [request setRequestMethod:requestType];
    
    [request setCompletionBlock:^{
        NSLog(@"%@",request.responseData);
        //根據返回數據類型,解析數據,暫定爲json解析
        NSString * string=[[NSString alloc]initWithData:request.responseData encoding:NSUTF8StringEncoding];
        block(string);
    }];
    
    [request setFailedBlock:^{
        UIAlertView *alert=[[UIAlertView alloc] initWithTitle:@"提示" message:@"請求失敗" delegate:self cancelButtonTitle:@"確定" otherButtonTitles:nil];
        [alert show];
        [alert release];
        block(@"failed");
    }];
    
    [request startAsynchronous];
}
+(NSMutableDictionary *)jsonValue :(NSString *)str{
    //json解析
    NSData *data=[str dataUsingEncoding:NSUTF8StringEncoding];
    return [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableLeaves error:nil];
}

@end


調用:


- (void)viewDidLoad
{
    [super viewDidLoad];
// Do any additional setup after loading the view, typically from a nib.
    NSMutableDictionary *dic=[[NSMutableDictionary alloc] init];
    [dic setObject:@"1" forKey:@"newwindow"];
    [dic setObject:@"strict" forKey:@"safe"];
    [dic setObject:@"dongstone" forKey:@"q"];
    [DataRequest dataWithDic:dic andRequestType:@"POST" andRequestCollectionAddressType:@"hk" andRequestSearchType:@"search" andBlock:^(NSString*requestStr) {
        NSLog(@"%@",[DataRequest jsonValue:requestStr]);
    }];
}



AFNetworking部分:

用AFNetworking來請求

@implementation DataRequestManager
+(void)dataWithDic:(NSMutableDictionary *)dic andRequestNameType:(NSString *)andRequestNameType andRequestName:(NSString *)requestName andRequestType :(NSString *)andRequestType andBlock:(void(^)(NSString *requsetStr))block{
    
    NSString *finalUrl=[NSString stringWithFormat:@"%@%@/%@",WEBSERVER,andRequestNameType,requestName];
    NSURL *baseURL = [NSURL URLWithString:finalUrl];
    AFHTTPClient *client = [[AFHTTPClient alloc] initWithBaseURL:baseURL];
    [client registerHTTPOperationClass:[AFJSONRequestOperation class]];
    
    if (dic==nil) {
        dic=[[[NSMutableDictionary alloc] init]autorelease];
    }
    
    NSMutableURLRequest *request=nil;
    if ([andRequestType isEqualToString:@"POST"]) {
        NSMutableDictionary *mudic=[[NSMutableDictionary alloc] init];
        for (NSString *key in [dic allKeys]) {
            NSString *value=[dic objectForKey:key];
            [mudic setValue:value forKey:key];
        }
        request = [client requestWithMethod:@"POST" path:nil parameters:mudic];
        
    }else{
        
        int urlCount=1;
        NSString *getUrl=[finalUrl stringByAppendingString:@"?"];
        for (NSString *key in [dic allKeys]) {
            NSString *value=[dic objectForKey:key];
            if (urlCount==[[dic allKeys] count]) {
                getUrl=[getUrl stringByAppendingString:[NSString stringWithFormat:@"%@=%@",key,value]];
            }else{
                getUrl=[getUrl stringByAppendingString:[NSString stringWithFormat:@"%@=%@&",key,value]];
            }
            urlCount++;
        }
        NSLog(@"%@",getUrl);
        NSURL *url = [NSURL URLWithString:[getUrl stringByAddingPercentEscapesUsingEncoding: NSUTF8StringEncoding]];
        request=[NSMutableURLRequest requestWithURL:url];
    }
    AFJSONRequestOperation *operation=[AFJSONRequestOperation JSONRequestOperationWithRequest:request success:^(NSURLRequest *request, NSHTTPURLResponse *response, id JSON) {
        NSLog(@"Success");
        NSLog(@"%@",JSON);
        SBJsonWriter *writer = [[SBJsonWriter alloc] init];
        NSString *jsonString=nil;
        jsonString=[writer stringWithObject:JSON];
        block(jsonString);
    } failure:^(NSURLRequest *request, NSHTTPURLResponse *response, NSError *error, id JSON) {
        [self showAlert:@"網絡連接失敗,請重試"];
        NSLog(@"%@",JSON);
        block(@"error");
        NSLog(@"Request Failed with Error: %@, %@", error, error.userInfo);
       
    }];
    [operation start];
    
}


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章