Network Programming in IOS and network programming in IOS

Source: Internet
Author: User

Network Programming in IOS and network programming in IOS

In the mobile Internet era, almost all applications require networks, such as QQ, Weibo, Netease news, Youku, and Baidu maps. Data Interaction and data updating can only be performed with the outside world through the network, only applications can maintain freshness and vitality. Without the network, there will be no data changes. No matter how gorgeous the appearance is, it will eventually become a waste of water. Next we will try to make a network request

Http programming is actually an http request. The longest method used for an http request is the get and post methods.

1> The get method is easier to understand than the post method. The get method can directly request a url, or splice parameters following the url to request a new url address. The value after the get method must be unicode encoded. The default enctype attribute of form is application/x-www-form-urlencoded. Binary files cannot be sent.
2> the post method is relatively complicated. First, set the key and value in the post method. All keys and values are spliced into a string of the key1 = value1 & key2 = value2 style, then the string is converted to binary and put into the body of the http request. When a request is sent, the request is sent along with the body to the server. Set the http request Content-Type to application/x-www-form-urlencoded. This is just a simple post request. Generally, this method is not used to send files (technically, you can also send files, that is, put files in key and value ). Next we will discuss more common methods for sending binary files via post.

 

1. Send a request

-(Void) viewDidLoad {// create a link. Do not splice the parameters to be passed. Because the server is set locally, two parameters are accepted: User Name and user password, therefore, I will pass two parameters here. The default value is "Get NSURL * url = [NSURL URLWithString: @" http: // 192.168.0.111/logo. php? UserName = jereh & pwd = 123 "]; // according to the training level e NSMutableURLRequest * request = [NSMutableURLRequest requestWithURL: url]; // link the network and send the request [NSURLConnection connectionWithRequest: self];}

2. Accept the returned data

After a network request, we need to accept the returned data. Here we need to implement a proxy method to accept the returned data. Here we need to implement the Protocol and define a variable NSData object.

The following proxy methods are frequently used:

# Pragma mark-NSURLConnectionDataDelegate # Call-(void) connection :( NSURLConnection *) connection didReceiveResponse :( NSURLResponse *) response {self. data = [NSMutableData data]; NSLog (@ "start to respond") ;}# pragma mark is called when receiving data from the server, because when the transmitted data is large, the system will accept the request multiple times, so we need to define a variable binary object to save the data for each request-(void) connection :( NSURLConnection *) connection didReceiveData :( NSData *) data {NSLog (@ "start receiving data"); [self. data appendData: data] ;}# call-(void) connectionDidFinishLoading (NSURLConnection *) connection {NSString * str = [[NSString alloc] initWithData: self. data encoding: NSUTF8StringEncoding]; NSLog (@ "% @", str) ;}# call-(void) connection (NSURLConnection *) When pragma mark accepts data errors *) connection didFailWithError :( NSError *) error {NSLog (@ "request error ");}

3. POST Method Request

The get method we used above. If we use the POST method for request, we only need to change the variable request to a variable request and then set the method.

-(Void) viewDidLoad {// create a request NSURL * url = [NSURL URLWithString: @ "http: // 192.168.0.111/logo. php? UserName = jereh & pwd = 123 "]; NSMutableURLRequest * request = [NSMutableURLRequest requestWithURL: url]; // set the request method. HTTPMethod = @ "POST"; // set the NSString * param = @ "userName = jereh & pwd = 123"; NSData * data = [param dataUsingEncoding: NSUTF8StringEncoding] parameter; // set the request Body request. HTTPBody = data; // link to the network and send the request [NSURLConnection connectionWithRequest: request delegate: self];}

4 send requests in synchronous Mode

In addition, we can use the synchronous method when sending a request. If we need to wait for the network request to end and execute an operation during the network request, we can take the synchronous request.

NSData * data= [NSURLConnection sendSynchronousRequest:request returningResponse:nil error:nil];

5 block asynchronous requests

In addition, when sending an asynchronous request, we can also adopt the block form, as shown below:

NSOperationQueue * queue=[NSOperationQueue mainQueue];    [NSURLConnection sendAsynchronousRequest:request queue:queue completionHandler:^(NSURLResponse *response, NSData *data, NSError *connectionError) {        NSString * str=[[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];}];

 

Author: Jerry Education
Source: http://www.cnblogs.com/jerehedu/
Copyright Disclaimer: The copyright of this article is shared by Yantai jereh Education Technology Co., Ltd. and the blog Park. You are welcome to repost it. However, you must keep this statement without the consent of the author and provide the original article connection clearly on the article page, otherwise, you are entitled to pursue legal liability.
Technical Consultation:

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.