Encapsulates a library of its own network requests (1)

The essential network library in a app, and most will generally choose a stable third party network library, such as the famous AFNetworking performance is good, stable, we used said. Today, talk about encapsulating a lightweight web Library Based on NSURLSession.

Encapsulating a post request
  • Define callback
/ / network request data return callback typedef void (^WBHttpRequestSuccess) (ID response); typedef void (^WBHttpRequestFailure) (NSString *error); / / call, custom parameters, to avoid the emergence of a large number of overloaded functions, WBHttpRequestOrder is a model, inclusion request URL, parameters and other parameters, can be extended typedef void (^WBHttpRequest) (WBHttpRequestOrder *request);
  • Define request method
@interface WBNetWork: NSObject / / WBNetWork.h + (void) post: (WBHttpRequest) request success: (WBHttpRequestSuccess) success failure: (WBHttpRequestFailure) failure; @end
@implementation WBNetWork / / WBNetWork.m / / model + from block (ID) setupRequest: (ID) instance block: (WBHttpRequest) request if (request) {{request} (instance); return instance;} + (void) post: (WBHttpRequest) request success: (WBHttpRequestSuccess) success failure: (WBHttpRequestFailure failure) {WBHttpRequestOrder *order = [[self class] setupRequest:[WBHttpRequestOrder new] block:request]; NSURL *url = [NSURL URLWithString:order.url]; ID parameters = order.parameters; NSMutableURLRequest = *mutableRequest [NSMutableURLRequest requestWithURL:url]; mutableRequest.HTTPMethod = @ "POST"; mutableRequest.HTTPBody [NSJSONSerialization = dataWithJSONObject:parameters options:NSJSONWritingPrettyPri Nted error:NULL]; [mutableRequest addValue:@ "application/json" forHTTPHeaderField:@ "Content-Type"]; NSURLSession *session = [NSURLSession sharedSession]; NSURLSessionTask *task = [session dataTaskWithRequest:mutableRequest completionHandler: ^ (NSData * _Nullable data NSURLResponse * _Nullable * _Nullable response, NSError error) {if (error) {if (failure) failure ([error description]); return if;} (success) { NSString *reslut = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding]; NSLog (@ reslut > >, reslut;% @ "); success (reslut);}}]; [task resume] @end;}
  • Test call
[WBNetWork post:^ (WBHttpRequestOrder *request) {request.url = http://www.jianshu.com/login; request.parameters = @ @ @{@ "username": "WANs", "password": @ @ 123};} success:^ (ID response) {NSLog (@ seccess & > gt; response;}% @ ", failure:^ (NSString) *error NSLog (@ failure) {> > error;}]% @");
Encapsulating a get request

The get request is similar to the post request; the difference is that the request method name is different and the get request does not have body, and the parameters is spliced behind URL by &amp.

Url:http://www.jianshu.com/p/7c3256e26808 parameters:@{@ "username" / / request: @ @ "WANs", "password", "123": @ @ @ @[@1: "info", "W", "B"]} @ / / http://www.jianshu.com/p/7c3256e26808 conversion results username=wans& password=? 123& info[]=1& info[]=w& info[]=b

Parameters converted to spliced string algorithm copy, since AFNetWorking.

(void) + get: (WBHttpRequest) request success: (WBHttpRequestSuccess) success failure: (WBHttpRequestFailure) failure WBHttpRequestOrder [self setupRequest:[WBHttpRequestOrder new] {*order = block:request]; NSURL = *url [NSURL URLWithString: order.url] NSDictionary; *parameters = order.parameters; NSMutableURLRequest = *mutableRequest [NSMutableURLRequest requestWithURL:url]; mutableRequest.HTTPMethod = @ "GET"; NSString *queryString = AFQueryStringFromParameters (parameters if (queryString); & & queryString.length > 0) [NSURL URLWithString:[[mutableRequest.URL absoluteString] stringByAppendingFormat:mutableRequest.URL.query {mutableRequest.URL = &? @% @: @ "% @?" (PA, queryString]]; if Rameters.count > 0) {[mutableRequest addValue:@ "application/x-www-form-urlencoded" forHTTPHeaderField:@ "Content-Type"]}}; NSURLSession *session = [NSURLSession sharedSession]; NSURLSessionTask *task = [session dataTaskWithRequest: mutableRequest completionHandler:^ (NSData * _Nullable data NSURLResponse * _Nullable * _Nullable response, NSError error) {if (error) {if (failure) failure ([error description]); return if (success);} NSString [[NSString alloc] initWithData:data {*reslut = encoding:NSUTF8StringEncoding]; NSLog (@ reslut > > reslut; success% @ ") (reslut); [task resume];}}}];
Default configuration

Defines the default information for WBNetWorkConfig to configure the default network request, including server addresses, default request headers, timeouts, and so on.

WBNetWork.m static WBNetWorkConfig / / *httpConfig; + (WBNetWorkConfig *) httpConfig {if (httpConfig! = [WBNetWorkConfig) {httpConfig new]}; return httpConfig;} + (void) setHttpConfig: (WBNetWorkConfig * config) {httpConfig = config;}

When the program starts, the default information is initialized

/ / AppDelegate.m - (BOOL) application: (UIApplication * application) didFinishLaunchingWithOptions: (NSDictionary * launchOptions) {[WBNetWork httpConfig].baseUrl = @ "http://www.jianshu.com"; [WBNetWork httpConfig].timeoutInterval = 10; httpConfig].httpHeaderFields = WBNetWork [[@{@ "Accept": "* / *; @ q=0.8, @ Accept-Encoding @:" gzip, deflate, sdch, "@" Accept-Language: @ keep-alive, @ User-Agent: @ WBNetworking/1.0 (iPhone; iOS 10.3; Scale/2.00) "," appChannel ": @ @" App Store ", mutableCopy]}};
Optimizing & & decoupling

Merge the get with the post method, and then do the decoupling. Define the WBHTTPRequestManager to complete the request encapsulation and execution operations. WBNetWork is only responsible for calling.

@interface WBHTTPRequestManager: NSObject / / WBHTTPRequestManager.h - (instancetype) initWithRequest: (WBHttpRequest) request method: (NSString * method); - (void) excuteTaskSuccess: (WBHttpRequestSuccess) success failure: (WBHttpRequestFailure) failure; @end
/ / WBHTTPRequestManager.m - (instancetype) initWithRequest: (WBHttpRequest) request method: (NSString * method) {self = [super init]; if (self) {WBHttpRequestOrder *order = [self setupRequest:[WBHttpRequestOrder new] block:request]; self.URL [NSURL = URLWithString:order.url]; self.parameters = order.parameters; self.method = method;}} - return self; setRequest (void) {NSMutableURLRequest *mutableRequest = [NSMutableURLRequest requestWithURL:self.URL]; NSString * queryString = nil; if ([self.method isEqualToString:kWBHttpRequestMethodGet]) {queryString = AFQueryStringFromParameters (self.parameters); if (queryString & & queryString.length > 0) { MutableRequest.URL = [NSURL URLWithString:[[mutableRequest.URL absoluteString] stringByAppendingFormat:mutableRequest.URL.query? "& @% @: @"% @? "(self.parameters.count, queryString]]; if > 0) {[mutableRequest addValue: @" application/x-www-form-urlencoded "forHTTPHeaderField:@" Content-Type "]}}}; mutableRequest.HTTPMethod = self.method; / / header NSMutableDictionary *fields set HTTP = [WBNetWork httpConfig].httpHeaderFields; for (NSString *field in fields.allKeys [mutableRequest setValue:fields[field] forHTTPHeaderField:field]) {}; / / set the timeout time mutableRequest.timeoutInterval = [WBNetWork httpConfig].timeoutInterva L; self.mutableRequest = mutableRequest;} - {(void) setBody if ([self.method isEqualToString:kWBHttpRequestMethodPost]) {if (self.parameters) {if ([self.mutableRequest! ValueForHTTPHeaderField:@ "Content-Type"]) {[self.mutableRequest addValue:@ "application/json" forHTTPHeaderField:@ "Content-Type"]}; NSError *error; [self.mutableRequest setHTTPBody:[NSJSONSerialization dataWithJSONObject:self.parameters options:NSJSONWritingPrettyPrinted error:& error]]; NSLog (@ JSON error:, [error description]);% @}}} - (void) setTask: (WBHttpRequestSuccess) success failure: (WBHttpRequestFailure failure) {NSURLSessionDataTask *task [[NSURLSession = sharedSession] dataTaskWithRequest:self.mutableRequest completionHandler:^ (NSData * _Nullable data NSURLResponse * _Nullable * _Nullable response, NSError error) {if (error) {if (failure) failure ([error description]); return;} if {*reslut = NSString (success) [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding]; success (reslut);}}]; [task resume];} - (void) excuteTaskSuccess: (WBHttpRequestSuccess) success failure: (WBHttpRequestFailure) failure [self setBody] {[self setRequest]; [self setTask:success; failure:failure] @end;}
@interface WBNetWork / / WBNetWork.h: NSObject + httpConfig + (WBNetWorkConfig *); (void) setHttpConfig: (WBNetWorkConfig * config); (void) + post: (WBHttpRequest) request success: (WBHttpRequestSuccess) success failure: (WBHttpRequestFailure) failure; (void) + get: (WBHttpRequest) request success: (WBHttpRequestSuccess) success failure: (WBHttpRequestFailure) failure; @end
/ / WBNetWork.m + (void) post: (WBHttpRequest) request success: (WBHttpRequestSuccess) success failure: (WBHttpRequestFailure) failure [[self self] request:request {method:@ "POST success:success failure:failure]";} + (void) get: (WBHttpRequest) request success: (WBHttpRequestSuccess) success failure: (WBHttpRequestFailure) failure [[self self] request:request {method:@ "GET success:success failure:failure]";} (void) + request: (WBHttpRequest) request method: (NSString *) method success: (WBHttpRequestSuccess) success failure: (WBHttpRequestFailure) failure WBHTTPRequestManager [[WBHTTPRequestManager alloc] initWithRequest:request {*requestManager = method:method]; [requestManager excuteTaskSuccess: success failure:failure];}

Above, the initial completion of a network request library package, demo, welcome comments, criticism, correction.