In the era of mobile internet, network communication is an essential function of mobile terminal. The use of network communication is also essential in our applications to enhance client-server interaction. This article provides a way to implement HTTP communication using Nsurlconnection.
Nsurlconnection provides two ways of communicating asynchronous requests and synchronous requests.
1. Asynchronous request
The new SendAsynchronousRequest:queue:completionHandler: Method in the iOS5.0 SDK Nsurlconnection class enables the iOS5 to support two asynchronous request methods. Let's start with the new class.
1) sendasynchronousrequest
IOS5.0 begins to support the Sendasynchronousreques method, using the following method:
[CPP]View Plaincopyprint?
- -(void) httpasynchronousrequest{
- Nsurl *url = [Nsurl urlwithstring:@"Http://url"];
- NSString *[email protected]"PostData";
- NSData *postdata = [post datausingencoding:nsasciistringencoding allowlossyconversion:yes];
- Nsmutableurlrequest *request = [Nsmutableurlrequest Requestwithurl:url];
- [Request sethttpmethod:@"POST"];
- [Request Sethttpbody:postdata];
- [Request settimeoutinterval:10.0];
- Nsoperationqueue *queue = [[Nsoperationqueue alloc]init];
- [Nsurlconnection Sendasynchronousrequest:request
- Queue:queue
- completionhandler:^ (Nsurlresponse *response, NSData *data, Nserror *error) {
- if (error) {
- NSLog (@"httperror:%@%d", Error.localizeddescription,error.code);
- }else{
- Nsinteger responsecode = [(Nshttpurlresponse *) response StatusCode];
- NSString *responsestring = [[NSString alloc] Initwithdata:data encoding:nsutf8stringencoding];
- NSLog (@"httpresponsecode:%d", responsecode);
- NSLog (@"Httpresponsebody%@", responsestring);
- }
- }];
- }
Sendasynchronousreques can easily use Nsurlrequest to receive callbacks to complete HTTP communication.
2) Connectionwithrequest
IOS2.0 began to support the Connectionwithrequest method, using the following:
[CPP]View Plaincopyprint?
- -(void) httpconnectionwithrequest{
- NSString *urlpath = [NSString stringwithformat:@"Http://url"];
- Nsurl *url = [Nsurl Urlwithstring:urlpath];
- Nsmutableurlrequest *request = [Nsmutableurlrequest Requestwithurl:url];
- [Nsurlconnection connectionwithrequest:request delegate:self];
- }
- -(void) connection: (Nsurlconnection *) theconnection didreceiveresponse: (nsurlresponse *) Response
- {
- Nsinteger responsecode = [(Nshttpurlresponse *) response StatusCode];
- NSLog (@"response length=%lld statecode%d", [response Expectedcontentlength],responsecode);
- }
- A delegate method called by the Nsurlconnection as data arrives. The
- Response data for a POST was only for useful for debugging purposes,
- So we just drop it on the floor.
- -(void) connection: (Nsurlconnection *) theconnection didreceivedata: (NSData *) Data
- {
- if (mdata = = nil) {
- Mdata = [[Nsmutabledata alloc] initwithdata:data];
- } Else {
- [Mdata Appenddata:data];
- }
- NSLog (@"response connection");
- }
- A delegate method called by the nsurlconnection if the connection fails.
- We shut down the connection and display the failure. Production Quality Code
- Would either display or log the actual error.
- -(void) connection: (Nsurlconnection *) theconnection didfailwitherror: (nserror *) Error
- {
- NSLog (@"Response error%@", [Error Localizedfailurereason]);
- }
- A delegate method called by the nsurlconnection when the connection have been
- Done successfully. We shut down the connection with a nil status, which
- Causes the image to be displayed.
- -(void) connectiondidfinishloading: (nsurlconnection *) theconnection
- {
- NSString *responsestring = [[NSString alloc] Initwithdata:mdata encoding:nsutf8stringencoding];
- NSLog (@"Response body%@", responsestring);
- }
Connectionwithrequest need delegate parameters, through a delegate to do the data download and request acceptance and connection status, here Delegate:self, so need to implement some methods of this class, Also define mdata to do the acceptance of the data.
Methods that need to be implemented:
1, get the return status, Baotou information.
[CPP]View Plaincopyprint?
- -(void) connection: (Nsurlconnection *) connection didreceiveresponse: (Nsurlresponse *) response;
2, connection failure, including failure.
[CPP]View Plaincopyprint?
- -(void) connection: (Nsurlconnection *) connection didfailwitherror: (Nserror *) error;
3. Receive data
[CPP]View Plaincopyprint?
- -(void) connection: (Nsurlconnection *) connection didreceivedata: (NSData *) data;
4. Data reception Complete
-(void) connectiondidfinishloading: (nsurlconnection *) connection;
Connectionwithrequest is more cumbersome to use, and iOS5.0 is not supported sendasynchronousrequest. A netizen has put forward aeurlconnection solution.
[HTML]View Plaincopyprint?
- Aeurlconnection is a simple reimplementation of the API for use on IOS 4. Used properly, it's also guaranteed to being safe against the deallocation problem, a thorny threading issue that affects Mo St Other networking libraries.
2. Synchronous request
The synchronous request data method is as follows:
[CPP]View Plaincopyprint?
- -(void) httpsynchronousrequest{
- Nsurlrequest * URLRequest = [nsurlrequest requestwithurl:[nsurl urlwithstring:@"http://google.com"]];
- Nsurlresponse * response = nil;
- Nserror * error = NIL;
- NSData * data = [Nsurlconnection sendsynchronousrequest:urlrequest
- Returningresponse:&response
- error:&error];
- if (Error = = nil)
- {
- //Processing data
- }
- }
Synchronizing request data can cause the main thread to block, and it is often not recommended when big data is requested or the network is not smooth.
As you can see from the code above, the steps to establish communication are basically the same regardless of the synchronous request or the asynchronous request:
1. Create Nsurl
2. Create a Request object
3. Create a nsurlconnection connection.
Once the nsurlconnection is created, an HTTP connection is created. The difference between an asynchronous request and a synchronous request is that an asynchronous request is created, the user can do other things, the request is executed on another thread, and the communication results and procedures are executed in the callback function. Synchronization requests are different and require the end user to be requested to do other things.
/*** @author Zhang Xingye * http://blog.csdn.net/xyz_lmn* iOS starter Group: 83702688* Android Development Advanced Group: 241395671* my Sina Weibo:@ Zhang Xingye tbow* * Reference: http://developer.apple.com/library/ios/#documentation/cocoa/conceptual/urlloadingsystem/tasks/ usingnsurlconnection.html#//apple_ref/doc/uid/20001836-bajeaieehttp://codewithchris.com/ tutorial-how-to-use-ios-nsurlconnection-by-example/http://kelp.phate.org/2011/06/ Ios-stringwithcontentsofurlnsurlconnect.html from:http://blog.csdn.net/xyz_lmn/article/details/8968182
"Go" iOS Learning Note (eight)--ios network communication HTTP Nsurlconnection