---restore content starts---
One: Send a simple GET request to the server
1. Synchronization
//send a GET request to the server//0. Request PathNsurl *url = [Nsurl urlwithstring:@"http://120.25.226.186:32812/login?username=122&pwd=1222"]; //1. Creating a Request object from a pathNsurlrequest *request = [Nsurlrequest Requestwithurl:url];//the request header is already included by default. //2. Sending the request//This method is a blocking method. NSDate *data =[nsurlconnection sendsynchronousrequest:request returningresponse:nil Error:nil]; //parse data into a stringNSString*str=[[NSString alloc] Initwithdata:data encoding:nsutf8stringencoding]; NSLog (@"-----------data%@", str); }
2. Asynchronous requests
//sends an asynchronous GET request to the server//0. Request PathNsurl *url = [Nsurl urlwithstring:@"http://120.25.226.186:32812/login?username=122&pwd=1222"]; //1. Creating a Request object from a pathNsurlrequest *request = [Nsurlrequest Requestwithurl:url];//the request header is already included by default. //2. Create a thread to send the request. [nsurlconnection sendasynchronousrequest:request Queue:[[nsoperationqueue alloc] init] Completionhandler:^ (Nsurlresponse * _nullable response, NSData * _nullable data, Nserror * _nullable connectionerror) {//when the request is sent in a new thread and the data is returned, it will come to this blockNSString*str=[[NSString alloc] Initwithdata:data encoding:nsutf8stringencoding]; NSLog (@"-----------data%@", str); NSLog (@"%@", [Nsthread CurrentThread]); }]; NSLog (@"------End---");
Printing results:
When the data is returned, block executes thread 3, and threads 2 because the request is asynchronous to execute the request.
---restore content ends---
2016-1-nsurlconnetction---GET request