Get request, can also send information to the server, there are parameters (Weibo user name, user ID)
1. Constructs the URL, the parameter joins directly after the URL connects
Nsurl *url = [Nsurl urlwithstring:@ "http://news-at.zhihu.com/api/3/news/4602734"];
2. Structuring the request
Keep request headers for GET requests in requests
Nsurlrequest *request = [Nsurlrequest Requestwithurl:url];
Parameters
(1) URL
(2) Caching policy
(3) Timeout period, after 120 seconds to abandon this request
Nsurlrequest *request = [Nsurlrequest requestwithurl:url cachepolicy:nsurlrequestreturncachedataelseload TIMEOUTINTERVAL:120];
Nsurlrequest immutable, unable to add the request header information dynamically
mutable objects
Nsmutableurlrequest *request = [Nsmutableurlrequest Requestwithurl:url];
(1) How to set the request
[Request sethttpmethod:@ "GET"];
(2) time-out period
[Request settimeoutinterval:120];
(3) Caching policy
[Request Setcachepolicy:nsurlrequestreturncachedataelseload];
(4) Set the request header other content
[Request setvalue:<# (NSString *) #> forhttpheaderfield:<# (NSString *) #>];
[Request addvalue:<# (NSString *) #> forhttpheaderfield:<# (NSString *) #>];
[Request setallhttpheaderfields:<# (Nsdictionary *) #>];
[Request setvalue:@ "gzip" forhttpheaderfield:@ "accept-encoding"]; Tell the service that the returned data needs to be compressed
3. Construction session
Nsurlsession *session = [Nsurlsession sharedsession];
4. Constructing task tasks to perform
/**
* Task
*
* @param data returned by
* @param response Response Head
* @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-to-data
Nsjsonserialization *jsondata = [nsjsonserialization datawithjsonobject:<# (ID) #> options:<# ( nsjsonwritingoptions) #> error:<# (nserror *__autoreleasing *) #>]
/*
Options
1. Read reading
Nsjsonreadingmutablecontainers generates mutable objects, does not set this option, the default is to create immutable objects
Nsjsonreadingmutableleaves Generating variable string mutablestring (ios7+ with bug)
Nsjsonreadingallowfragments allows the outermost layer of JSON data to be not a dictionary or an array
2. Write writing
Nsjsonwritingprettyprinted generated JSON data is formatted, has line breaks, and is highly readable
*/
Data-to-JSON
NSString *datastr = [[NSString alloc] Initwithdata:data encoding:nsutf8stringencoding];
NSLog (@ "Data:%@", DATASTR);
}
}];
5.
[Task resume];
Nsurlsession (a) GET request