Ios network learning ------ 1get post asynchronous request

Source: Internet
Author: User

Network request steps:

Get request:

# Pragma mark-this is a private method. Try not to directly use attributes in the method, because attributes are generally associated with the interface, we can use the attribute # pragma mark Get logon method through parameters-(void) loginWithGet :( NSString *) name pwd :( NSString *) pwd {// 1 OK URL NSURL NSString * urlString = [NSString stringWithFormat: @ "www.baidu.com? Username = % @ & password = % @ ", name, pwd]; NSLog (@" % @ ", urlString); // in the url, if you want to convert a Chinese character to a percent sign format, it is provided to the server for decoding (if the server uses UTF-8 ). UrlString = [urlString stringByAddingPercentEscapesUsingEncoding: NSUTF8StringEncoding]; NSLog (@ "% @", urlString); NSURL * url = [NSURL URLWithString: urlString]; // 2 create a request NSURLRequest * request = [NSURLRequest requestWithURL: url]; // 3 create and start a connection to the nsulconnection NSURLConnection * conn = [NSURLConnection connectionWithRequest: request delegate: self]; [conn start]; // start the connection. This is because a network request has occurred. This is an asynchronous connection request. After the request is sent, it is processed by the proxy. // Prepare the server notification and prepare the intermediate 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 it in get mode. // The previous row is in get mode, and the following is in post mode. // 1. Confirm the NSURL NSString * urlString = [NSString stringWithFormat: @ "www.baidu.com"]; NSURL * url = [NSURL URLWithString: urlString]; // 2 create a request NSMutableURLRequest (this is required for post) NSMutableURLRequest * request = [NSMutableURLRequest requestWithURL: url]; // 1) post request method. The default network request method is get, therefore, if we use post requests, we must declare the request method. [Request setHTTPMethod: @ "POST"]; // 2) the data body of the post request. If the data body in the post request contains Chinese characters, no conversion is required. Because the ataUsingEncoding method has 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 create and start the connection to nsulconnection NSURLConnection * conn = [NSURLConnection connectionWithRequest: request delegate: self]; [conn start]; // start the connection. This is because the network request has occurred. This is an asynchronous connection request. After the request is sent, it is processed by the proxy. // Prepare the server notification and prepare the intermediate data self. serverData = [NSMutableData data];}



After start, use the proxy To achieve subsequent processing:

// 4 process network requests through proxy and follow the protocol # pragma mark Network Data Processing proxy, there are a total of five proxy methods # pragma mark proxy method 1 receives the response from the server, the server is about to transmit data, and the client is ready for receiving-(void) connection :( NSURLConnection *) connection didReceiveResponse :( NSURLResponse *) response {}# pragma mark proxy method 2 receives data transmitted by the server, it may be executed multiple times-(void) connection :( NSURLConnection *) connection didReceiveData :( NSData *) data {// concatenate the data transmitted each time. The intermediate data [self. serverData appendData: data] ;}# pragma mark proxy method 3 receives data and performs subsequent processing- (Void) connectionDidFinishLoading :( NSURLConnection *) connection {// perform subsequent processing on the Data spliced in method 2. NSString * str = [[NSString alloc] initWithData: self. serverData encoding: NSUTF8StringEncoding]; // process the string returned by the server. // 1 the location where the user name is located found from str: nsange range = [str rangeOfString: @ "User Name"]; // The string (User Name) found in the nsange table) NSLog (@ "% @", NSStringFromRange (range); NSString * msg = nil; if (range. location> 0) {// The string following the username, until the end NSString * name = [str substringFromIndex :( range. location + range. length)]; NSLog (@ "% @", name); // 3 Welcome Back msg = [NSString stringWithFormat: @ "Welcome: % @", name];} else {msg = @ "the user name or password is incorrect. Please try again! ";} NSLog (@" % @ ", str); // a message is displayed, indicating that the user has successfully logged on. UIAlertView * alertView = [[UIAlertView alloc] initWithTitle: @" message: msg delegate: nil cancelButtonTitle: @ "OK" otherButtonTitles: nil, nil]; [alertView show]; // clear data self. serverData = nil ;}# pragma mark proxy method 4 f server request failed, many reasons (w network environment, etc.);-(void) connection :( NSURLConnection *) connection didFailWithError :( NSError *) error {NSLog (@ "Network Connection Request error % @", error. localizedDescription ); // Localized Error Message description .} # Pragma mark d proxy method 5 sends data to the server. This method is only applicable to post, especially when uploading files. /* The first parameter is the connection, the second parameter is the data body sent, the third parameter indicates the data to be written as a whole, and the fourth parameter indicates the data to be written as expected. The server uses these values to know how much data has been transferred and how much data is expected */-(void) connection :( NSURLConnection *) connection didSendBodyData :( NSInteger) bytesWritten totalBytesWritten :( NSInteger) totalBytesWritten totalBytesExpectedToWrite :( NSInteger) totalBytesExpectedToWrite {NSLog (@ "send data to server");} @ end


Related Article

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.