自定义NetWorkRequest类 继承自NSObject ,并定义一个Block

定义post 请求方法


#import <Foundation/Foundation.h>

///后台参数回调代码块
typedef void (^CallDataBlock)(NSData * _Nullable data, NSURLResponse * _Nullable response, NSError * _Nullable error);

@interface NetWorkRequest : NSObject

///post请求
+ ( void ) sendAsynchronousRequest:(NSString *) urlString parameter:(NSMutableDictionary *) parameter CallDataBlock:(CallDataBlock) CallDataBlock;

@end


实现post请求方法

+ ( void ) sendAsynchronousRequest:(NSString *) urlString parameter:(NSMutableDictionary *) parameter CallDataBlock:(CallDataBlock) CallDataBlock  {
    
    //编码
    urlString = [urlString stringByAddingPercentEncodingWithAllowedCharacters:[NSCharacterSet URLQueryAllowedCharacterSet]];
    
    ///urlString 转url
    NSURL *url = [NSURL URLWithString:urlString];
    
    
    NSMutableURLRequest *_Nullable request = [NSMutableURLRequest requestWithURL:url
                                             cachePolicy:NSURLRequestReloadRevalidatingCacheData
                                         timeoutInterval:3];
	///设置请求方式为post
    request.HTTPMethod = @"post";
	
	NSMutableDictionary *dic = [[NSMutableDictionary alloc] init];
    
	///	设置传参数json类型给后台
    [dic setValue:@"application/json" forKey:@"Content-Type"];
    ///	设置请求行
    [request setAllHTTPHeaderFields:dic];    

    NSMutableData *postBody = [NSMutableData data];
    ///字典转json 再转 data
    [postBody appendData:[[parameter mj_JSONString] dataUsingEncoding:NSUTF8StringEncoding]];
	///设置请求正文
    [request setHTTPBody:postBody];
    
    
	///	获得session实例
    NSURLSession *session = [NSURLSession sharedSession];
    ///	发起请求
    NSURLSessionDataTask *dataTask = [session dataTaskWithRequest:request completionHandler:CallDataBlock];
    
    [dataTask resume];

}



发起请求
	/// 请求地址 参数.字典类型
	[NetWorkRequest sendAsynchronousRequest:@"" parameter:@{} CallDataBlock:^(NSData * _Nullable data, NSURLResponse * _Nullable response, NSError * _Nullable error) {
        这里的data就是请求返回回来的数据
        ///data.mj_JSONString 是后台返回的json字符串
        
    }];


Logo

魔乐社区(Modelers.cn) 是一个中立、公益的人工智能社区,提供人工智能工具、模型、数据的托管、展示与应用协同服务,为人工智能开发及爱好者搭建开放的学习交流平台。社区通过理事会方式运作,由全产业链共同建设、共同运营、共同享有,推动国产AI生态繁荣发展。

更多推荐