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];
    
}


  • 2
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值