IOS development network programming HTTP/FTP connection

Source: Internet
Author: User

1. cfhttp

You can use cfhttp APIs to create HTTP requests. Generally, HTTP request methods include get, head, put, post, delete, tracr, connect, and options. Cfhttp requests generally take four steps:

 

  • Use the cfhttpmessagecreaterequest function to generate a cfhttp message object.
  • Use the cfhttpmessagesetbody function to set the message content
  • Use the cfhttpmessagesetheaderfieldvalue function to set the Message Header
  • Use cfhttpmessagecopyserializedmessage to serialize messages
Only http post requires the message content, which is the form data to be submitted.

 

 

Example: Create an http get request. The serialized request should be sent through the write stream.

Cfstringref requestheader = cfstr ("connection ");

Cfstringref requestheadervalue = cfstr ("close ");

Cfstringref requestbody = cfstr ("");

 

Cfstringref url = cfstr ("http://www.baidu.com /");

Cfstringref requestmethod = cfstr ("get ");

 

Cfurlref requesturl = cfurlcreatewithstring (kcfallocatordefault, URL, null );

Cfhttpmessageref request = cfhttpmessagecreaterequest (kcfallocatordefault, requestmethod, requesturl, kcfhttpversion1_1 );

Cfhttpmessagesetbody (request, requestbody );

Cfhttpmessagesetheaderfieldvalue (request, requestheader, requestheadervalue );

 

Cfdataref serializedrequest = cfhttpmessagecopyserializedmessage (request );

 

The procedure for creating an HTTP request is similar to that for creating a request. The difference is that cfhttpmessagecreateresponse function is used instead of cfhttpmessagecreaterequest.

You can use a cfreadstream object to serialize and send a cfhttp request. When a cfreadstream object is used, the message is serialized and sent when the read stream is opened, so that the response can be conveniently obtained. As follows:

Cfhttpmessageref request = cfhttpmessagecreaterequest (kcfallocatordefault, requestmethod, requesturl, kcfhttpversion1_1 );

Cfhttpmessagesetbody (request, requestbody );

Cfhttpmessagesetheaderfieldvalue (request, requestheader, requestheadervalue );

Cfreadstreamref readstream = cfreadstreamcreateforhttprequest (kcfallocatordefault, request );

Cfreadstreamopen (readstream );

 

Call cfreadstreamcopyproperty to obtain the Response Message from the read stream. The Code is as follows:

Cfhttpmessageref response = cfreadstreamcopyproperty (readstream, kcfstreampropertyhttpresponseheader );

Use the cfhttpmessagecopyresponsestatusline function to obtain the complete status line, as shown below:

Cfstringref statusline = cfhttpmessagecopyresponsestatusline (response );

Alternatively, use the cfhttpmessagegetresponsestatuscode function to obtain the status code, as shown below:

Uint32 errcode = cfhttpmessagegetresponsestatuscode (response );

To obtain the returned data, you can use the cfreadstreamsetclient method to set the callback function and add readstream to the run loop. The callback function saves the data read each time (for example, there is an nsmutabledata variable data). After reading the data, the Code is as follows:

If (kcfstreameventhasbytesavailable = eventtype)

{

Uint8 buff [255];

Int length = cfreadstreamread (stream, buff, 254 );

[Data appendbytes: buff length: length];

If (kcfstreameventendencountered = eventtype)

{

// Read completed to process read data

}

}

 

If the received data is a Chinese string, select the encoding when creating the nsstring, such as utf8 or gb2312 encoding, as shown below:

Nsstring * string = [[nsstring alloc] initwithdata: data encoding: 0x80000632]; // gb2312 Encoding

When you use cfreadstreamcreateforhttprequest to create a read stream, streaming redirection is disabled by default. If the request connection is redirected, an error occurs. Its Status Code is 300 ~ 307. If you receive a redirection error, You need to disable the stream, create a new stream, enable redirection, and enable the stream. As follows:

Cfreadstreamref readstream = cfreadstreamcreateforhttprequest (kcfallocatordefault, request );

If (cfreadstreamsetproperty (readstream, kcfstreampropertyhttpshouldautoredirect, kcfbooleantrue) = false)

{

// Handle errors

}

Cfreadstreamopen (myreadstream );

 

2. cfftp

Cfftp also uses cfreadstream to transmit FTP data. Use the cfreadstreamcreatewithftpurl method to create an FTP request. In this way, a cfreadstreamref object is created to read the data sent by the FTP server. The Code is as follows:

Cfstringref url = cfstr ("ftp://ftp.example.com/file.txt ");

Cfurlref requesturl = cfurlcreatewithstring (kcfallocatordefault, URL, null );

Cfreadstreamref readstream = cfreadstreamcreatewithftpurl (kcfallocatordefault, requesturl );

Next, use the cfreadstreamsetclient method to set the callback function to read data, and then add readstream to the program's run loop.

If FTP requires user name and password authentication, use the cfreadstreamsetproperty method to set the kcfstreampropertyftpusername and kcfstreampropertyftppassword attributes.

To download a file to a local device, you can use the cfwritestreamcreatewithfile method to create a write stream pointing to the local file and write the received data.

The uploaded file is similar to the downloaded file, but the read stream and write stream are used in turn. The cfwritestreamcreatewithftpurl method is used to create the write stream and the cfreadstreamcreatewithfile method is used to create the read stream.

The method for creating a remote directory is similar to that for uploading files, except that the cfurl object is set to a path rather than a file.

The method for obtaining the directory list is similar to that for downloading files. After the data is read to the cache, use cfftpcreateparsedresourcelisting to parse the read.

 

3. nsurlconnection

Cfnetwork is a relatively low-level interface. Although it is flexible to use, it is not easy to use. Most programs only need to create simple requests to obtain a file on the Internet, so it is more convenient to use nsurlconnection because it does not need to deal with sockets, streams, and callback functions, it is replaced by a more familiar delegation mechanism.

Create an nsurl object:

Nsnrl * url = [nsurl urlwithstring: @ "http://www.baidu.com/"];

The nsurl object is used to create the nsurlrequest object, as follows:

Nsurlrequest * request = [[nsurlrequest alloc] initwithurl: URL cachepolicy: nsurlrequestreturncachedataelseloadtimeoutinterval: 60.0];

 

The following cache policies are available.

(1) nsurlrequestuseprotocolcachepolicy: use the default Cache Policy of the relevant protocol.

(2) nsurlrequestreloadignoringlocalcachedata: requests must be reloaded regardless of the local cache.

(3) nsurlrequestreloadignoringlocalandremotecachedata: not only must the local cache be ignored, but the remote proxy or middleware cache be ignored when the Protocol permits.

(4) nsurlrequestreturncachedataelseload: the cache data is preferentially used. When the cache does not exist, the request is loaded.

(5) nsurlrequestreturncachedatadontload: load the cached data only. If the cache does not exist, it is not requested. It can be understood as an offline mode.

(6) nsurlrequestreloadrevalidatingcachedata: the cached data is loaded only when the cached data does not expire. Otherwise, the cached data is requested and refreshed.

 

 

After creating the nsurlrequest object, you can create the nsurlconnection object as follows:

Nsurlconnection * connection = [[nsulconnection alloc] initwithrequest: Request delegate: Self];

 

This is an asynchronous call. nsurlconnection will send a request in the background. By setting the delegate parameter, a notification will be sent when there is data. Some delegate methods are used to handle different events in the connection process.

When the service host has a response to start sending data, the didreceiveresponse: method will be called. Here we can do some initialization work. For example, there is an nsmutabledata type data object to store data. Here we can set the object length to 0, as shown below:

-(Void) connection :( nsurlconnection *) connection didreceiverespose :( nsurlresonse *) Response

{

[Data setlength: 0];

}

When data is received, the didreceivedata: method is called. You can add the data to the end of the nsmutabledata object as follows:

-(Void) connection :( nsurlconnection *) connection didreceivedata :( nsdata *) incomingdata

{

[Data appenddata: incomingdata];

}

 

When data loading is complete, connecitiondidfinshloading is called to process incoming data. Here, we use string processing as an example. The input in the example application may be an image or any other type of object.

 

-(Void) connectiondidfinishloading :( nsurlconnection *) Connection

{Nsstring * string = [[nsstring alloc] initwithdata: data encoding: nsutf8stringencoding]; nslog (string); [data release];} when the connection or data transmission fails, the didfailwitherror method is called as follows:-(void) connection :( nsurlconnection *) connection didfailwitherror :( nserror *) error {nslog (@ "query failed with error :% @", [error localizeddescription]); [data release];}

 

 

 

 

 

 

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.