Encapsulation of a network request data Class Based on AFNetWorking and afnetworking
1. Create a new class that inherits from the NSObject class. In the. h file
# Import "AFHTTPRequestOperationManager. h"
// Define two blocks to receive successful and failed requests
Typedef void (^ DownLoadFinishedBlock) (id responseObj );
Typedef void (^ DownLoadFialedBlock) (NSError * error );
@ Interface NetManager: NSObject
// Get Request Method Encapsulation
+ (Void) doGetWithUrlStr :( NSString *) urlString contentType :( NSString *) type finished :( DownLoadFinishedBlock) finished failure :( DownLoadFialedBlock) fialed;
// Method encapsulation of Post requests
+ (Void) doPostWithUrlStr :( NSString *) urlString parameters :( NSDictionary *) dic contentType :( NSString *) type finished :( DownLoadFinishedBlock) finished failure :( DownLoadFialedBlock) fialed;
2. The following is the implementation of the encapsulation method:
# Import "NetManager. h"
@ Implementation NetManager
// Get Request Method
+ (Void) doGetWithUrlStr :( NSString *) urlString contentType :( NSString *) type finished :( DownLoadFinishedBlock) finished failure :( DownLoadFialedBlock) fialed {
// Create a manager object
AFHTTPRequestOperationManager * manager = [AFHTTPRequestOperationManager];
// Set the request data type
Manager. responseSerializer. acceptableContentTypes = [NSSet setWithObjects: type, nil];
[Manager GET: urlString parameters: nil success: ^ (AFHTTPRequestOperation * operation, id responseObject ){
// The request is successful.
Finished (responseObject );
} Failure: ^ (AFHTTPRequestOperation * operation, NSError * error ){
// Request failed
Fialed (error );
}];
}
// Post Request Method
// Description: parameters: parameter, which is the parameter that needs to be sent to the backend server when a post request is used. Here we should encapsulate the data in a dictionary type, then pass the dictionary as a parameter.
+ (Void) doPostWithUrlStr :( NSString *) urlString parameters :( NSDictionary *) dic contentType :( NSString *) type finished :( DownLoadFinishedBlock) finished failure :( DownLoadFialedBlock) fialed
{
// Create a manager object
AFHTTPRequestOperationManager * manager = [AFHTTPRequestOperationManager];
// Set the request data type
Manager. responseSerializer = [AFHTTPResponseSerializer serializer];
Manager. responseSerializer. acceptableContentTypes = [NSSet setWithObjects: type, nil];
[Manager POST: urlString parameters: dic success: ^ (AFHTTPRequestOperation * operation, id responseObject ){
Finished (responseObject );
} Failure: ^ (AFHTTPRequestOperation * operation, NSError * error ){
Fialed (error );
}];
}
@ End