NSURLSession (1) GET request, nsurlsessionget
// GET request, which can also send information to the server, as well as parameters (Weibo user name and user ID)
// 1. Construct a URL. The parameters are directly spliced after url Connection.
NSURL * url = [NSURL URLWithString: @ "http://news-at.zhihu.com/api/3/news/4602734"];
// 2. Construct the Request
// Save the get request header in the request
// NSURLRequest * request = [NSURLRequest requestWithURL: url];
// Parameters
// (1) url
// (2) Cache Policy
// (3) the request will be abandoned after 120 seconds
// NSURLRequest * request = [NSURLRequest requestWithURL: url cachePolicy: NSURLRequestReturnCacheDataElseLoad timeoutInterval: 120];
// NSURLRequest is unchangeable and cannot dynamically add request header information
// Variable object
NSMutableURLRequest * request = [NSMutableURLRequest requestWithURL: url];
// (1) set the Request Method
[Request setHTTPMethod: @ "GET"];
// (2) Timeout
[Request setTimeoutInterval: 120];
// (3) Cache Policy
[Request setCachePolicy: NSURLRequestReturnCacheDataElseLoad];
// (4) set other content in the Request Header
// [Request setValue: <# (NSString *) #> forHTTPHeaderField: <# (NSString *) #>];
// [Request addValue: <# (NSString *) #> forHTTPHeaderField: <# (NSString *) #>];
// [Request setAllHTTPHeaderFields: <# (NSDictionary *) #>];
[Request setValue: @ "gzip" forHTTPHeaderField: @ "Accept-Encoding"]; // inform the service that the returned data must be compressed.
// 3. Construct a Session
NSURLSession * session = [NSURLSession sharedSession];
// 4. Construct the task to be executed
/**
* Task
*
* @ Param data: returned data
* @ Param response Header
* @ Param error message
*
*/
NSURLSessionDataTask * task = [session dataTaskWithRequest: request completionHandler: ^ (NSData * data, NSURLResponse * response, NSError * error ){
If (error = nil ){
/*
NSString * dataStr = [[NSString alloc] initWithData: data encoding: NSUTF8StringEncoding];
NSLog (@ "data: % @", dataStr );
*/
// Json --> data
// NSJSONSerialization * jsonData = [NSJSONSerialization dataWithJSONObject: <# (id) #> options: <# (NSJSONWritingOptions) #> error: <# (NSError * _ orauteleasing *) #>]
/*
Options:
1. Read reading
NSJSONReadingMutableContainers generates a variable object. If this option is not set, an immutable object is created by default.
NSJSONReadingMutableLeaves generates a variable string MutableString (iOS7 + bug)
NSJSONReadingAllowFragments allows the outermost layer of json data not a dictionary or Array
2. Write writing
NSJSONWritingPrettyPrinted formatted json data with line breaks and high readability
*/
// Data --> json
NSString * dataStr = [[NSString alloc] initWithData: data encoding: NSUTF8StringEncoding];
NSLog (@ "data: % @", dataStr );
}
}];
// 5.
[Task resume];