Web Service network communication between clients and servers in iOS
When you open the Sina Weibo app on your mobile phone or the zhihu app, do you want to find out where the images and data displayed on your mobile phone come from? What method is used for implementation? Okay, so next we will introduce how it is implemented and what the process is like.
When we browse Weibo websites that follow or are close to our friends, the images and data are not shown out of thin air, but are obtained by sending a request to the server via your client and then the Sina Weibo server returns the local data, through data parsing, you can display and even operate on the client. These are what we usually call Web Services. Web Service is a Service provided through the Web protocol to ensure that application services on different platforms can interoperate and provide different services for client applications. Currently, there are three mainstream Web Service technologies: REST, SOAP, and XML-RPC. Now we mainly introduce REST Web Service.
REST is translated as "representation state transfer", "representation" is the page seen by the client, the page Jump is the status transfer, the client obtains the page to be displayed by requesting the URI. REST is generally based on existing protocols and standards such as HTTP, URI, XML, and HTML.
REST Web Service is a Web Service that uses HTTP and follows the REST principle. Request the Web Service to use URI to locate the resource. The data exchange format with Web Service is very flexible, such as JSON and XML. The HTTP request methods supported by Web Service, including POST, GET, PUT, or DELETE.
Requests implemented by the synchronous GET method:
In the previous article, JSON is locally parsed. Now it is parsed from the data returned by the server request. Next, let's take a look at the main methods of Web Service requests.
-(Void) startRequest {NSString * strURL = [[NSString alloc] initWithFormat: @ "requested server address"]; NSURL * url = [NSURL URLWithString: [strURL URLEncodedString]; NSURLRequest * request = [[NSURLRequest alloc] initWithURL: url]; NSData * data = [NSURLConnection sendSynchronousRequest: request returningResponse: nil error: nil]; NSLog (@ "request completed... "); NSDictionary * resDict = [NSJSONSerialization JSONObjectWithData: data options: NSJSONReadingAllowFragments error: nil]; [self reloadView: resDict];}
InitWithFormat: Specifies the request URL. This is the Web Service that the URL directs. The next line of code uses the strURL string to create an NSURL object. The parameter is [strURL URLEncodedString]. The strURL string calls the URLEncodedString method to convert the string to a URL string, during Internet transmission, the URL cannot contain special characters such as Chinese characters. This method is used to convert these characters to URL encoding with percent signs (the URL encoding of the "<" symbol is "% 3C ").