iOS Web learning------1get Post Asynchronous request

Source: Internet
Author: User

Steps for Network requests:

GET Request:

#pragma mark  -This is a private method, try not to use the property directly in the method, as the general attribute is associated with the interface, we can use the attribute #pragma mark Get login Method-(void) Loginwithget :(NSString *) name pwd: (NSString *) pwd{    //1 determine address nsurl    nsstring *urlstring = [NSString stringwithformat:@] www.baidu.com?username=%@&password=%@ ", name, PWD];    NSLog (@ "%@", urlstring);    URL, assume that the include Chinese characters need to be converted to a format with a percent semicolon, provided to the server decoding (assuming that the server is using Utf-8).    urlstring = [urlstring stringbyaddingpercentescapesusingencoding:nsutf8stringencoding];    NSLog (@ "%@", urlstring);    Nsurl *url = [Nsurl urlwithstring:urlstring];    2 Establishment Request Nsurlrequest    nsurlrequest *request = [Nsurlrequest requestwithurl:url];    3 Establish and start the connection nsrulconnection    nsurlconnection *conn = [Nsurlconnection connectionwithrequest:request delegate:self ];    [Conn start];  Start the connection, which is where the network request has occurred. This is an asynchronous connection request, and when the request is sent out, it is referred to the agent for processing.        //server notification ready, ready for transit data    self.serverdata = [nsmutabledata data];}

POST request:

-(void) login{NSLog (@ "come here");    NSString *username = Self.nameTextField.text;    NSString *pwd = Self.passwordTextField.text;   [Self loginwithget:username pwd:pwd];    Call with Get//The above line is get method, the following is the Post method.    1 determine address nsurl nsstring *urlstring = [NSString stringwithformat:@ "www.baidu.com"];        Nsurl *url = [Nsurl urlwithstring:urlstring];    2 Build Request Nsmutableurlrequest (post requires this) nsmutableurlrequest *request = [Nsmutableurlrequest Requestwithurl:url];    1) The Post request method, the network request is the Get method by default, so suppose we use the POST request, must declare the request way.    [Request sethttpmethod:@ "POST"]; 2) The data body of the POST request, when the data body in the post request, is assumed to have Chinese, does not need to convert.    Since the Atausingencoding method has been implemented transcoding.    NSString *bodystr = [NSString stringwithformat:@ "username=%@&password=%@", username, pwd];    Convert nstring to NSData nsdata *body = [Bodystr datausingencoding:nsutf8stringencoding];    NSLog (@ "Body data%@", body);        [Request Sethttpbody:body]; 3 Establish and start the connection nsrulconnection nsurlconnection *conn = [Nsurlconnection connectionwithrequest:request Delegate:self];  [Conn start]; Start the connection, which is where the network request has occurred.        This is an asynchronous connection request, and when the request is sent out, it is referred to the agent for processing. Server notification readiness, ready for transit data Self.serverdata = [Nsmutabledata data];}



After start, through the agent<Nsurlconnectiondatadelegate> To achieve the possible processing:

4 through the proxy method to process the network request, abide by the protocol #pragma mark Network data processing agent, the total common has five proxy methods #pragma mark Proxy Method 1 Accept the response to the server, the server to transmit data, the client is ready to receive-(void ) Connection: (Nsurlconnection *) connection didreceiveresponse: (Nsurlresponse *) response{} #pragma mark Proxy method 2 receive Server    Transmitted data, may run multiple times-(void) connection: (Nsurlconnection *) connection didreceivedata: (NSData *) data{//splicing data for each transfer, need to transfer data [Self.serverdata Appenddata:data];}     #pragma mark Proxy Method 3 received the data, do perhaps processing-(void) connectiondidfinishloading: (nsurlconnection *) connection{//On the Method 2 splicing data, do perhaps processing.            NSString *str = [[NSString alloc] InitWithData:self.serverData encoding:nsutf8stringencoding];    The string returned by the server is processed.  1 location of the username found from str nsrange range = [str rangeofstring:@ "username"];        Nsrange stores the location and length of the found string (username) NSLog (@ "%@", Nsstringfromrange (range));    NSString *msg = nil; if (Range.location > 0) {//2 username after string, until the end nsstring *name = [str substringfromindex: (Range.locati        On +range.length)]; NSLog (@ "%@ ", name);    3 Welcome back msg= [NSString stringwithformat:@ "Welcome:%@", name]; }else {msg = @ "username or password error, please try again!    ";    } NSLog (@ "%@", str); Prompt user Login successful Uialertview *alertview = [[Uialertview alloc] initwithtitle:@ "hint" message:msg delegate:nil cancelbuttontitle    : @ "OK" otherbuttontitles:nil, nil];        [Alertview show]; Empty data Self.serverdata = nil;} #pragma mark Proxy Method 4 Fserver request failed for very many reasons (w network environment, etc.);-(void) connection: (Nsurlconnection *) connection Didfailwitherror: ( Nserror *) error{NSLog (@ "Network connection request error%@", error.localizeddescription);//Localized error information descriptive narrative. #pragma the Mark D Proxy method 5 sends data to the server, the secondary method applies only to post, especially to upload files. /* The first parameter is the connection, the second is the data body to be sent, the third represents the overall data to be written, and the fourth represents the data that is expected to be written. Through these values, the server knows how much this has passed, how much has been passed, and how many */-(void) connection are expected to wear: (Nsurlconnection *) connection didsendbodydata: (Nsinteger) Byteswritten Totalbyteswritten: (nsinteger) Totalbyteswritten totalbytesexpectedtowrite: (NSInteger) totalbytesexpectedtowrite{NSLog (@ "Send data to Server");} @end


iOS Web learning------1get Post Asynchronous request

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.