ASIHttpRequest的使用

//get请求

+ (void)getWithASIURL:(NSString *)urlString parmas:(NSDictionary *)params completeBlock:(void (^)(id responseObj))success failure:(void (^)(NSError *error))failure{

    //处理GET请求

    NSString *urlStr = [HOST stringByAppendingString:urlString];

    NSArray *keys=[params allKeys];

    for (int i=0; i<keys.count; i++) {

        NSString *key=[keys objectAtIndex:i];

        NSString *values=[params valueForKey:key];

        urlStr= [urlStr stringByAppendingFormat:@"&%@=%@",key,values];

    }

    NSURL *url=[NSURL URLWithString:urlString];

    ASIFormDataRequest *request=[ASIFormDataRequest requestWithURL:url];

    [request setRequestMethod:@"GET"];

    [request setTimeOutSeconds:10];

    

    [request setCompletionBlock:^{

        NSData *data = [request responseData];

        NSDictionary *dic = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableLeaves error:nil];

        success(dic);

    }];

    [request setFailedBlock:^{

        NSError *error = [request error];

        failure(error);

    }];

    [request startAsynchronous];

}

 

//post请求

+ (void)postWithASIURL:(NSString *)urlString parmas:(NSDictionary *)params completeBlock:(void (^)(id responseObj))success failure:(void (^)(NSError *error))failure{

    

    ASIFormDataRequest *request = [ASIFormDataRequest requestWithURL:[NSURL URLWithString:[HOST stringByAppendingString:urlString]]];

    NSData *jsonData = [NSJSONSerialization dataWithJSONObject:params options:(NSJSONWritingPrettyPrinted) error:nil];

    [request setRequestMethod:@"POST"];

    [request setPostBody:[NSMutableData dataWithData:jsonData]];

    [request addRequestHeader:@"Accept" value:@"application/json"];

    [request addRequestHeader:@"content-type" value:@"application/json"];

    [request setResponseEncoding:NSUTF8StringEncoding];

    

    [request setCompletionBlock:^{

        NSData *jsonData = [request.responseString dataUsingEncoding:NSUTF8StringEncoding];

        NSDictionary *dic = [NSJSONSerialization JSONObjectWithData:jsonData options:NSJSONReadingMutableLeaves error:nil];

        success(dic);

    }];

    [request setFailedBlock:^{

        NSError *error = [request error];

        failure(error);

    }];

    

    [request startAsynchronous];

}

你可能感兴趣的:(ASIHTTPRequest)