HTTPRequest

版权声明:本文为博主原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。
本文链接:https://blog.csdn.net/Morris_/article/details/93603272
#import "VSSHTTPRequest.h"

@implementation VSSHTTPRequest

+ (void)POST:(NSURL *)url
  parameters:(NSDictionary *)parameters
     success:(void (^)(NSDictionary * _Nonnull))success
     failure:(void (^)(NSError * _Nonnull))failure {

    NSMutableURLRequest *request = [[NSMutableURLRequest alloc] initWithURL:url];
    //HTTPMethod
    [request setHTTPMethod:@"POST"];
    //Content-Type
    [request setValue:@"application/x-www-form-urlencoded;charset=UTF-8" forHTTPHeaderField:@"Content-Type"];
    //HTTPBody
    NSString *paramsString = [VSSHTTPRequest convertDictToString:parameters];
    NSData *data = [paramsString dataUsingEncoding:NSASCIIStringEncoding allowLossyConversion:YES];
    [request setHTTPBody:data];

    NSURLSession *session = [NSURLSession sharedSession];
    NSURLSessionDataTask *task = [session dataTaskWithRequest:request completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) {
        
        if (error || !data || !response || ((NSHTTPURLResponse *)response).statusCode != 200) {
            
            dispatch_async(dispatch_get_main_queue(), ^{
                if (failure) {
#ifdef DEBUG
                    NSLog(@"request failure : %@",error);
#else
#endif
                    failure(error);
                }
            });
            return;
        }
        
        NSString *jsonString = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
        NSDictionary *dict = [VSSHTTPRequest jsonStringToDictionary:jsonString];
        
        dispatch_async(dispatch_get_main_queue(), ^{
            if (success) {
#ifdef DEBUG
                NSLog(@"request result : %@",dict);
#else
#endif
                success(dict);
            }
        });
    }];
    [task resume];
}

+ (NSString *)convertDictToString:(NSDictionary *)dict {
    if (!dict) {
        return @"";
    }
    
    NSMutableString * converString = [NSMutableString string];
    for (id key in [dict allKeys])
    {
        NSString *value = [NSString stringWithFormat:@"%@",[dict objectForKey:key]];
        if (converString.length == 0)
        {
            [converString appendFormat:@"%@=%@",key,[VSSHTTPRequest gtm_stringByEscapingForURLArgument:value]];
        }
        else
        {
            [converString appendFormat:@"&%@=%@",key,[VSSHTTPRequest gtm_stringByEscapingForURLArgument:value]];
        }
    }
    return converString;
}
+ (id)jsonStringToDictionary:(NSString *)jsonString {
    if (!jsonString) {
        return nil;
    }
    NSData *jsonData = [jsonString dataUsingEncoding:NSUTF8StringEncoding];
    NSError *err;
    id obj = [NSJSONSerialization JSONObjectWithData:jsonData options:NSJSONReadingMutableContainers error:&err];
    if(err) {
        return nil;
    }
    return obj;
}


+ (NSString *)gtm_stringByEscapingForURLArgument:(NSString *)value {
//     Encode all the reserved characters, per RFC 3986
//     (<http://www.ietf.org/rfc/rfc3986.txt>)
//    CFStringRef escaped =
//    CFURLCreateStringByAddingPercentEscapes(kCFAllocatorDefault,
//                                            (CFStringRef)value,
//                                            NULL,
//                                            (CFStringRef)@"!*'();:@&=+$,/?%#[]",
//                                            kCFStringEncodingUTF8);
//#if defined(__has_feature) && __has_feature(objc_arc)
//    return CFBridgingRelease(escaped);
//#else
//    return [(NSString *)escaped autorelease];
//#endif
    NSCharacterSet *set = [NSCharacterSet characterSetWithCharactersInString:@"!*'();:@&=+$,/?%#[]"];
    return [value stringByAddingPercentEncodingWithAllowedCharacters:set];
}

+ (NSString *)gtm_stringByUnescapingFromURLArgument:(NSString *)value {
//    NSMutableString *resultString = [NSMutableString stringWithString:value];
//    [resultString replaceOccurrencesOfString:@"+"
//                                  withString:@" "
//                                     options:NSLiteralSearch
//                                       range:NSMakeRange(0, [resultString length])];
//    return [resultString stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
    return [value stringByRemovingPercentEncoding];
}

@end

get请求例:

	//get请求拼接参数
    NSString *stringURL = [NSString stringWithFormat:@"http://t-api-xxx.xxxl.com/edu/school/site-url?name=%@",self.textField.text];
    //URL编码
    stringURL = [stringURL stringByAddingPercentEncodingWithAllowedCharacters:[NSCharacterSet characterSetWithCharactersInString:@"#%^{}\"[]|\\<> "].invertedSet];
    //发起网络请求
    NSMutableURLRequest *request = [[NSMutableURLRequest alloc] initWithURL:[NSURL URLWithString:stringURL]];
    [request setHTTPMethod:@"GET"];
    [request setValue:@"application/x-www-form-urlencoded;charset=UTF-8" forHTTPHeaderField:@"Content-Type"];
    NSURLSessionDataTask *task = [[NSURLSession sharedSession] dataTaskWithRequest:request completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) {
        if (error || !data || !response || ((NSHTTPURLResponse *)response).statusCode != 200) {
            dispatch_async(dispatch_get_main_queue(), ^{
                  //...
            });
        }
        else {
            NSString *jsonString = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
            NSData *jsonData = [jsonString dataUsingEncoding:NSUTF8StringEncoding];
            NSError *err;
            NSDictionary *dict = [NSJSONSerialization JSONObjectWithData:jsonData options:NSJSONReadingMutableContainers error:&err];
            dispatch_async(dispatch_get_main_queue(), ^{
             		//...
            });
        }
    }];
    [task resume];

展开阅读全文

没有更多推荐了,返回首页