ios 获取后台接口数据(Post请求,返回json)

自定义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字符串
        
    }];


发布了31 篇原创文章 · 获赞 30 · 访问量 7375

猜你喜欢

转载自blog.csdn.net/qq_41586150/article/details/104364669