Nsurlconnection (ios2.0-ios9.0) Brief introduction

Source: Internet
Author: User

Nsurlconnection Four steps to use:

1, Prepare Url-nsurl

2. Create Request-Nsrequest

3. Sending requests (including asynchronous and synchronous)

4. Callback

1     //4 ways to create a request:2     //MARK:-Scenario One: Create Request object (default request length 60s)3     //nsurlrequest *request = [Nsurlrequest requestwithurl:url];4     5     //MARK:-Scenario Two: Create a Request object to set both the cache policy and the timeout length6     /*7 CachePolicy:8 nsurlrequestuseprotocolcachepolicy = 0, using the HTTP default cache policy9      Ten nsurlrequestreloadignoringlocalcachedata = 1, load only the latest network data (stock) One       A nsurlrequestreturncachedataelseload = 2, load cache first, then load network data -       - nsurlrequestreturncachedatadontload = 3, load only cached data (offline application: Offline map, offline video) the      */ -     //nsurlrequest *request = [nsurlrequest requestwithurl:url cachepolicy:0 timeoutinterval:15]; -      -     //MARK:-Scenario Three: Using Nsmutableurlrequest: You can modify the request method (default is get, you can change to post) +Nsmutableurlrequest *requestm =[Nsmutableurlrequest Requestwithurl:url]; -     //Requestm.httpmethod = @ "POST";//Modify to POST request +     //additional request header information, only variable (nsmutableurlrequest) to modify A[Requestm SetValue:@"IPhone AppleWebKit"Forhttpheaderfield:@"user-agent"]; at      -     //MARK:-Scenario IV: Similar to scenario two, with cache policy and timeout length on a scenario three basis -Nsmutableurlrequest *requestm2 = [Nsmutableurlrequest requestwithurl:url cachepolicy:0timeOutInterval: the];
 1  //  Nsurlresponse Description:  2  //  1, MIMEType: File type on server (Content-type inside equivalent response header)  3  //  2, Expectedcontentlength: The total size of the file on the server (used when downloading the progress calculation) . Span style= "COLOR: #008080" >4  //  3, suggest Edfilename: After the file is downloaded, the  5  // Span style= "COLOR: #008000" > subclass Nshttpurlresponse:  6  //  StatusCode: status code, 200 for success, 304 unmodified, to read from cache  

Below a complete small demo, use Nsurlconnection to load Baidu, and use WebView to display:

1 #import "ViewController.h"2 3 /*4 nsurlconnection use four steps:5 1, prepare Url-nsurl6 2. Create Request-Nsrequest7 3. Sending requests (including asynchronous and synchronous)8 4. Callback9  */Ten  One @interfaceViewcontroller () A  -@property (Weak, nonatomic) iboutlet UIWebView *WebView; -  the @end -  - @implementationViewcontroller -  +- (void) Viewdidload { - [Super Viewdidload]; + [self loaddata]; A } at  -  -- (void) loaddata{ -     //Prepare the URL -Nsurl *url = [Nsurl urlwithstring:@"https://www.baidu.com"]; -      in     //MARK:-Scenario One: Create Request object (default request length 60s) -     //nsurlrequest *request = [Nsurlrequest requestwithurl:url]; to      +     //MARK:-Scenario Two: Create a Request object to set both the cache policy and the timeout length -     /* the CachePolicy: * nsurlrequestuseprotocolcachepolicy = 0, using the HTTP default cache policy $      Panax Notoginseng nsurlrequestreloadignoringlocalcachedata = 1, load only the latest network data (stock) -       the nsurlrequestreturncachedataelseload = 2, load cache first, then load network data +       A nsurlrequestreturncachedatadontload = 3, load only cached data (offline application: Offline map, offline video) the      */ +     //nsurlrequest *request = [nsurlrequest requestwithurl:url cachepolicy:0 timeoutinterval:15]; -      $     //MARK:-Scenario Three: Using Nsmutableurlrequest: You can modify the request method (default is get, you can change to post) $Nsmutableurlrequest *requestm =[Nsmutableurlrequest Requestwithurl:url]; -     //Requestm.httpmethod = @ "POST";//Modify to POST request -     //additional request header information, only variable (nsmutableurlrequest) to modify the[Requestm SetValue:@"IPhone AppleWebKit"Forhttpheaderfield:@"user-agent"]; -     Wuyi     //MARK:-Scenario IV: Similar to scenario two, with cache policy and timeout length on a scenario three basis theNsmutableurlrequest *requestm2 = [Nsmutableurlrequest requestwithurl:url cachepolicy:0timeOutInterval: the]; -      Wu     //Parameter 1: Request Object -     //Parameter 2: Callback Queue About     //Parameter 3: Completion callback $[Nsurlconnection sendasynchronousrequest:requestm queue:[nsoperationqueue Mainqueue] completionHandler:^ ( Nsurlresponse * _nullable response, NSData * _nullable data, Nserror *_nullable Connectionerror) { -         //Response: Response header -         //Data: Response body (binary) -         //connectionerror: Error message A          +         //Nsurlresponse Introduction: the         //1. MIMEType: File type on server (Content-type in equivalent response header) -         //2. Expectedcontentlength: The total size of the file on the server (used when downloading the progress calculation) $         //3, suggestedfilename: File download down, save the name of the the         //sub-class Nshttpurlresponse: the         //StatusCode: status code, 200 = success, 304 unmodified, read from cache the          the         //MARK:-Judging the wrong way one -         /* in if (connectionerror! = nil) { the NSLog (@ "Network request error:%@", connectionerror); the return; About          } the nshttpurlresponse *httpurlresponse = (Nshttpurlresponse *) response; the if (Httpurlresponse.statuscode = = | | httpurlresponse.statuscode = = 304) { the NSLog (@ "Response head:%@", response); + NSLog (@ "Response body:%@", data); - nsstring *htmlstr = [[NSString alloc] Initwithdata:data encoding:nsutf8stringencoding]; the          Bayi [Self.webview loadhtmlstring:htmlstr baseurl:url]; the          } the          */ -         //MARK:-Judging the wrong way two -         if(Connectionerror = = Nil && Data! =Nil) { theNSLog (@"response header:%@", response); theNSLog (@"response body:%@", data); theNSString *htmlstr =[[NSString alloc] Initwithdata:data encoding:nsutf8stringencoding]; the              - [Self.webview loadhtmlstring:htmlstr baseurl:url]; the}Else{ theNSLog (@"Network request error:%@", connectionerror); the         }94     }]; the } the  the @end

Nsurlconnection (ios2.0-ios9.0) Brief introduction

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.