Network requests for iOS programming

Source: Internet
Author: User

Network requests have get requests and post requests, and the get and post implementations can be implemented synchronously or asynchronously. See if a request is a GET or post to see if there is a request body behind the URL.

Get and post difference 1.get request URL All clear text display security is not high
2.get the URL of the request request has a limit of about 255 characters
3.post request URL Not only is there a request URL can also carry the request body this request body is in the form of nsdata security is higher
4.post request No limit on the number of characters get synchronous and get asynchronous synchronous requests are not able to do other things when requesting data asynchronous requests can do other things when requesting data. Get synchronization Request Step 1. Create a URL object 1 nsstring *oldurl = Ksearchurl;Note: If you request a URL with a Chinese language that must be re-encoded
NSString *newurl = [Oldurl stringbyaddingpercentescapesusingencoding:nsutf8stringencoding];

Then turn the string into a URL object

Nsurl *url = [Nsurl Urlwithstring:newurl];

2. Make a network request

Nsmutableurlrequest *request = [Nsmutableurlrequest requestwithurl:url cachepolicy: ( Nsurlrequestuseprotocolcachepolicy) timeOutInterval:30.0];

CachePolicy Cache Policy General Select the default policy timeoutinterval request time-out default is GET request if you want to set it needs to be a mutable request

3. Set the request type

[Request Sethttpmethod:@ "GET"];

4. Establish a link to receive binary data

Nsurlresponse *response =*error =*data = [Nsurlconnection sendsynchronousrequest:request Returningresponse:&response error:&error];

Response server-returned error message that describes the data of the server if you do not need to describe the server data and error messages can be filled nil

You can then convert the requested data into JSON format

Nsmutabledictionary *datadic = [nsjsonserialization jsonobjectwithdata:data options: ( nsjsonreadingmutablecontainers) Error:nil];    NSLog (@ "%@", Datadic);

The Get asynchronous request step is the same as the first three steps of a synchronous request, with the main difference being to establish a link

The first step is to create a URL object and then use the URL object to create a request type of get

There are two ways to get a request 1. Proxy method 2.block method

Asynchronous proxy methods require adherence to a protocol nsurlconnectiondatadelegate, which can be declared as a property for ease of use

nsurlconnection * connection;

delegate: self];
Open the asynchronous request [Self.connection start], the specific code is as follows:
@interfaceGetviewcontroller () <nsurlconnectiondatadelegate, nsurlconnectiondelegate>//declares a variable data for stitching the complete method@property (nonatomic, retain) Nsmutabledata *data;//declares a link property used to terminate a network request@property (nonatomic, retain) nsurlconnection *connection;@end@implementationGetviewcontroller- (void) dealloc{//If this page is destroyed then to terminate the network request[_connection Cancel];    [_data release];    [_connection release]; [Super Dealloc];}#pragmaMark-nsurlconnectiondatadelegate 4 Proxy Methods-(void) Connection: (Nsurlconnection *) connection didreceiveresponse: (Nsurlresponse *) response{//Trigger method link successfully initialized variable dataSelf.data =[Nsmutabledata data]; NSLog (@"received an array of servers stating that the link was successful");}- (void) Connection: (Nsurlconnection *) connection didreceivedata: (NSData *) data{//Splicing Data[Self.data Appenddata:data]; NSLog (@"triggered when data is received");}- (void) Connectiondidfinishloading: (Nsurlconnection *) connection{//This method triggers the proof that data is complete//you can then parse the dataNsmutabledictionary *datadic =[Nsjsonserialization JSONObjectWithData:self.data options: (nsjsonreadingmutablecontainers) Error:nil]; NSLog (@"%@", Datadic); NSLog (@"has finished loading");}- (void) Connection: (Nsurlconnection *) connection didfailwitherror: (Nserror *) error{NSLog (@"viewing error messages");}#pragmaMark-Asynchronous Request block method//Asynchronous Request Block method//Create an asynchronous request link[Nsurlconnection sendasynchronousrequest:request queue:[nsoperationqueue Mainqueue] completionHandler:^ ( Nsurlresponse *response, NSData *data, Nserror *connectionerror) {NSLog (@"%d", [Nsthread ismainthread]);//asynchronous requests are equivalent to opening a child thread to load the data//Data Load complete call block back to main thread}];

Post Async is similar to the Get method with the proxy method and the Block method proxy method and the Block method the first three steps are the same

//1. Create a URL objectNsurl *url =[Nsurl Urlwithstring:knewslisturl];//2. Create a mutable request with a URL objectNsmutableurlrequest * request = [Nsmutableurlrequest Requestwithurl:url cachepolicy: Nsurlrequestuseprotocolcachepolicy timeOutInterval:30.0]; //3. Set the request type[Request Sethttpmethod:@"POST"]; //Note: Carry a request body to this requestNSData *pramdata =[Knewslistparam datausingencoding:nsutf8stringencoding]; //carry to the request body[Request Sethttpbody:pramdata]; //Use this request to create a link and get the returned dataNsurlresponse *response =Nil; Nserror*error =Nil; NSData*data = [Nsurlconnection sendsynchronousrequest:request returningresponse:&response error:&ERROR]; //parsing DataNsmutabledictionary *datadic =[nsjsonserialization jsonobjectwithdata:data options:nsjsonreadingmutablecontainers Error:nil]; NSLog (@"%@", Datadic); Post Async is similar to the Get method with the proxy method and the Block method proxy method and the Block method the first three steps are the same//Create URL Word a Create URL objectNsurl *url =[Nsurl Urlwithstring:knewslisturl]; //create a request with a URL objectNsmutableurlrequest *request = [Nsmutableurlrequest requestwithurl:url cachepolicy: Nsurlrequestuseprotocolcachepolicy timeOutInterval:30.0]; //set the type of request[Request Sethttpmethod:@"POST"]; //bring the request body to this requestNSData *pramdata =[Knewslistparam datausingencoding:nsutf8stringencoding]; [Request Sethttpbody:pramdata];//use the Block method to complete one-step request[Nsurlconnection sendasynchronousrequest:request queue:[nsoperationqueue Mainqueue] completionHandler:^ ( Nsurlresponse *response, NSData *data, Nserror *connectionerror) {        //data is the resolution of the request to be completed .Nsmutabledictionary *datadic =[nsjsonserialization jsonobjectwithdata:data options:nsjsonreadingmutablecontainers Error:nil]; NSLog (@"%@", Datadic); Create a link with a request use the Proxy method to implement one-step request data Self.connection= [Nsurlconnection connectionwithrequest:requestDelegate: Self]; //Open Link[self.connection start];#pragmaMark-Proxy Method-(void) Connection: (Nsurlconnection *) connection didreceiveresponse: (Nsurlresponse *) response{//Initialize DataSelf.data =[Nsmutabledata data]; NSLog (@"return server information to prove that the link was successful");}- (void) Connection: (Nsurlconnection *) connection didreceivedata: (NSData *) data{//Splicing Data[Self.data Appenddata:data]; NSLog (@"returns a bit of data multiple times each time it executes");}- (void) Connectiondidfinishloading: (Nsurlconnection *) connection{NSLog (@"%@", Self.data); NSLog (@"data can be parsed at the completion request");}- (void) Connection: (Nsurlconnection *) connection didfailwitherror: (Nserror *) error{NSLog (@"return error message");}#import "PostViewController.h"@interfacePostviewcontroller () <nsurlconnectiondatadelegate, nsurlconnectiondelegate>//declaring a mutable data for asynchronous requests@property (nonatomic, retain) Nsmutabledata *data;//declare attribute to terminate the request when the interface is destroyed@property (nonatomic, retain) nsurlconnection *connection;@end@implementationPostviewcontroller- (void) dealloc{[_connection Cancel];    [_connection release];    [_data release]; [Super Dealloc];}

The network request code has a lot of duplicate code and we can encapsulate it ourselves. I personally feel that encapsulation is a bit similar to math in extracting common divisor, putting the same place to write a method and then giving different parameters

Encapsulating a network request you can think about what is out there, what's inside it. Write a little bit more, the package is left to friends.

Network requests for iOS programming

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.