Common classes
NSURL: //请求地址NSURLRequest: //一个NSURLRequest对象就代表一个请求,它包含的信息有:一个NSURL对象请求方法、请求头、请求体请求超时… …NSMutableURLRequest://NSURLRequest的子类NSURLConnection //负责发送请求,建立客户端和服务器的连接发送NSURLRequest的数据给服务器,并收集来自服务器的响应数据
Nsurlconnection Steps to use
The steps to send a request using Nsurlconnection are simple
Create a Nsurl object, set the request path
Incoming Nsurl creates a Nsurlrequest object, sets the request header and the request body
Send Nsurlrequest using nsurlconnection
Nsurlconnection Sending requests
Nsurlconnection Common Send Request method has the following several
Sync Request
+ (NSData *)sendSynchronousRequest:(NSURLRequest *)request returningResponse:(NSURLResponse **)responseerror:(NSError **)error;
Asynchronous requests: Depending on how the server returns data, it can be divided into 2 different types of
Block callback
+ ( void ) Sendasynchronousrequest: (Nsurlrequest* ) Request queue :(nsoperationqueue* ) queue completionhandler: (void (^) (Nsurlresponse* response, NSData * data , Nserror* connectionerror)) handler;
代理- (id)initWithRequest:(NSURLRequest *)request delegate:(id)delegate;+ (NSURLConnection*)connectionWithRequest:(NSURLRequest *)request delegate:(id)delegate;- (id)initWithRequest:(NSURLRequest *)request delegate:(id)delegate startImmediately:(BOOLNO的情况下,需要调用start方法开始发送请求- (void)start;成为NSURLConnection的代理,最好遵守NSURLConnectionDataDelegate协议
Nsurlconnectiondatadelegate Proxy method
//开始接收到服务器的响应时调用- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response;//接收到服务器返回的数据时调用(服务器返回的数据比较大时会调用多次)- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data;//服务器返回的数据完全接收完毕后调用- (void)connectionDidFinishLoading:(NSURLConnection *)connection;//请求出错时调用(比如请求超时)- (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error;
Nsmutableurlrequest variable URL Request
Nsmutableurlrequest is a subclass of nsurlrequest, the common method is
//设置请求超时等待时间(超过这个时间就算超时,请求失败)- (void)setTimeoutInterval:(NSTimeInterval)seconds;//设置请求方法(比如GET和POST)- (void)setHTTPMethod:(NSString *)method;//设置请求体- (void)setHTTPBody:(NSData *)data;//设置请求头- (void)setValue:(NSString *)value forHTTPHeaderField:(NSString *)field;
Create get and POST requests
//Create a GET requestNSString*URLSTR = [@"Http://192.168.1.102:8080/Server/login?username=123&pwd=123"Stringbyaddingpercentescapesusingencoding:nsutf8stringencoding];Nsurl*url = [NsurlURLWITHSTRING:URLSTR]; Nsmutableurlrequest *request = [Nsmutableurlrequest Requestwithurl:url];//Create POST requestNSString*URLSTR = @"Http://192.168.1.102:8080/Server/login";Nsurl*url = [NsurlURLWITHSTRING:URLSTR]; Nsmutableurlrequest *request = [Nsmutableurlrequest requestwithurl:url];request. HttpMethod= @"POST";//Request BodyNSString*BODYSTR = @"Username=123&pwd=123"; request. Httpbody= [Bodystr datausingencoding:nsutf8stringencoding];
Resume Download Instance
#Import "ViewController.h"#Import "DACircularProgressView.h"@interfaceViewcontroller () <nsurlconnectiondatadelegate>-(ibaction) Download: (UIButton *) sender;/** * File handle object for writing data * /@property(Nonatomic, Strong) Nsfilehandle *writehandle;/** * Total size of the file * /@property(Nonatomic, assign)Long LongTotallength;/** * File size that is currently written * /@property(Nonatomic, assign)Long LongCurrentlength;/** * Connection Object * *@property(Nonatomic, Strong) Nsurlconnection *conn;@property(Nonatomic, weak) Dacircularprogressview *circleview;@end@implementationviewcontroller-(void) viewdidload{[SuperViewdidload];additional setup after loading the view, typically from a nib.Dacircularprogressview *circleview = [[Dacircularprogressview alloc] init]; Circleview.frame = CGRectMake ( -, -, -, -); Circleview.progresstintcolor = [Uicolor Redcolor]; Circleview.tracktintcolor = [Uicolor Bluecolor]; Circleview.progress =0.0000001; [Self.view Addsubview:circleview]; Self.circleview = Circleview;} #pragma mark-nsurlconnectiondatadelegate Proxy method/** * Call when request fails (Request timeout, network exception) * * @param Error cause */- (void) Connection: (Nsurlconnection *) connection didfailwitherror: (Nserror *) error{NSLog (@"Didfailwitherror");}/** * 1. The response received from the server will be called * * @param Response Response */- (void) Connection: (Nsurlconnection *) connection didreceiveresponse: (Nsurlresponse *) response{if(self.currentlength)return;//file pathNSString *caches = [Nssearchpathfordirectoriesindomains (nscachesdirectory, Nsuserdomainmask, YES) lastObject]; NSString *filepath = [Caches stringbyappendingpathcomponent:@"Videos.zip"];//Create an empty file into the sandboxNsfilemanager *mgr = [Nsfilemanager Defaultmanager]; [Mgr Createfileatpath:filepath Contents:nil Attributes:nil];//Create a file handle to write dataSelf.writehandle = [Nsfilehandle Filehandleforwritingatpath:filepath];//Get the total size of the fileSelf.totallength = Response.expectedcontentlength;}/** * 2. Called when the Entity data returned by the server is received (specific content, this method may be called multiple times) * * @param data returned this time * *- (void) Connection: (Nsurlconnection *) connection didreceivedata: (NSData *) data{//Move to the last side of the file[Self.writehandle Seektoendoffile];//write data to sandbox[Self.writehandle Writedata:data];//The length of the cumulative fileSelf.currentlength + = Data.length; Self.circleView.progress = (Double) Self.currentlength/self.totallength;}/** * 3. Call after loading (the server's data is fully returned) */- (void) Connectiondidfinishloading: (nsurlconnection *) connection{self.currentlength =0; Self.totallength =0;//Close file[Self.writehandle CloseFile]; Self.writehandle = nil;} -(ibaction) Download: (UIButton *) Sender {//State inversionsender.selected =!sender.isselected;//Breakpoint Continuation //Breakpoint Download if(sender.selected) {//Continue (start) Download //1.URLNsurl *url = [Nsurl urlwithstring:@"Http://localhost:8080/MJServer/resources/videos.zip"];//2. RequestNsmutableurlrequest *request = [Nsmutableurlrequest Requestwithurl:url];//Set the request headerNSString *range = [NSString stringwithformat:@"bytes=%lld-", Self.currentlength]; [Request Setvalue:range forhttpheaderfield:@"Range"];//3. Download (an asynchronous request is automatically initiated when the Conn object is created)Self.conn = [nsurlconnection connectionwithrequest:request delegate:self]; }Else{//Pause[Self.conn Cancel]; Self.conn = nil; }}@end
Nsurlconnection Summary
1. Publish an asynchronous request on--BlockCallback + (void)sendasynchronousrequest:(nsurlrequest*)Request Queue:(Nsoperationqueue*)Queue Completionhandler:(void(^) (Nsurlresponse*Response,NSData*Data,Nserror*Connectionerror))Handler//Request: Requests to be sent//Queue: General use of the home row, storageHandlerThis task//Handler: This will be called automatically when the request is complete.Block2. UsingnsurlconnectionBasic steps to send a request1>CreateURLNsurl*URL= [Nsurl urlwithstring:@"http://4234324/5345345"];2>CreateRequestnsurlrequest*Request= [nsurlrequest Requestwithurl:url];3>Send Request [nsurlconnection sendasynchronousrequest:request Queue:queue Completionhandler: ^(Nsurlresponse*Response,NSData*Data,Nserror*Connectionerror) {4> processing the data returned by the server}];
iOS Development-Nsurlconnection implementation of a breakpoint to continue download