Communicating with HTTP server (communicating with HTTP Servers)

Source: Internet
Author: User

This article explains how to create, send, and receive HTTP requests and responses.

Create a Cfhttp request

An HTTP request is a message that is executed by the remote server by the method, the object (URL) of the action, themessage header, and the body of the message. The method is usually one of the following:GET, HEAD, PUT, POST, DELETE, TRACE, CONNECT or OPTIONS. Creating an HTTP request with Cfhttp is divided into four steps:

    • Generating cfhttp Message objects using the cfhttpmessagecreaterequest function
    • Using the cfhttpmessagesetbody function to set the message body
    • Using the cfhttpmessagesetheaderfieldvalue function to set the message header
    • Serialization of messages by calling the cfhttpmessagecopyserializedmessage function

The sample code resembles the code in Listing 3-1.

Listing 3-1 Creating an HTTP Request

cfstringref bodystring = Cfstr ("");                                        Usually used for POST datacfdataref bodydata = cfstringcreateexternalrepresentation (Kcfallocatordefault, bodystring, kCFStringEncodingUTF8, 0); Cfstringref headerfieldname = cfstr ("X-my-favorite-field"); Cfstringref Headerfieldvalue = cfstr ("Dreams"); Cfstringref url = cfstr ("http://www.apple.com"); Cfurlref Myurl = cfurlcreatewithstring (kcfallocatordefault, URL, NULL); Cfstringref Requestmethod = cfstr ("GET");                               Cfhttpmessageref myrequest = Cfhttpmessagecreaterequest (Kcfallocatordefault, Requestmethod, MyURL, Kcfhttpversion1_1); Cfdataref Bodydataext = cfstringcreateexternalrepresentation (Kcfallocatordefault, BodyData, kCFStringEncodingUTF8, 0 ); Cfhttpmessagesetbody (Myrequest, Bodydataext); Cfhttpmessagesetheaderfieldvalue (Myrequest, Headerfieldname, Headerfieldvalue); Cfdataref myserializedrequest = Cfhttpmessagecopyserializedmessage (myrequest); 


cfhttpmessagecreaterequestReturns the Message object reference (myrequest) and the message body (Bodydata) sent together toCfhttpmessagesetbody。 and then callCfhttpmessagesetheaderfieldvalueUse the same Message object reference, header (Headerfield) name and value of the setting (value)。 The head parameter is a cfstring.objects, such asContent-length, the value parameter is a cfstringobjects such as1260.Finally, call theCfhttpmessagecopyserializedmessageSerialized messages, sent to the recipient by a write stream, seehttp://www.apple.com. In this sample code, by calling thecfurlcreatewithstring,URLis first converted into a cfurlobject. And then callcfhttpmessagecreaterequest, there are four parameters:KcfallocatordefaultSpecifies that the default system memory allocator is used to create the message app,RequestmethodSpecify methods, such asPOSTmethod,MyurlUsed to specify a URL, for example,http://www.apple.com,kcfhttpversion1_1Specify a messageHTTPversion is1.1.

Note: The request body is usually omitted. The request principal is typically used for a post request that contains post data . It can also be used for other types of requests related to HTTP extensions, such as WebDAV. For more information, see RFC 2616.

When a message is no longer needed, the message object is freed and the message is serialized. See example code for listing 3-2

Listing 3-2 Releasing an HTTP Request

Cfrelease (myrequest); Cfrelease (Myurl); Cfrelease (URL); Cfrelease (myserializedrequest); myrequest = Null;myserializedrequest = NULL;

Create a cfhttp response

Create an HTTPthe steps of the response are related to creating aHTTPThe requested steps are almost identical. The only difference is that the calling functionCfhttpmessagecreateresponse, but notcfhttpmessagecreaterequest, both use the same parametersDeserializing an incoming HTTP request

Deserialize an incoming HTTP request, use the cfhttpmessagecreateempty function, create an empty message, and set theisrequest parameter to TRUE Specifies that an empty request message is created. Then call the cfhttpmessageappendbytes function to add the incoming message to the empty message. cfhttpmessageappendbytes Deserializes the message and removes any control information that might be contained.

Continue to do so until the cfhttpmessageisheadercomplete function returns TRUE. If you do not check whether cfhttpmessageisheadercomplete returns TRUE, the message may be incomplete or untrusted. Listing 3-3 can see examples of the use of these two functions.

Manifest 3-3 Deserialization message

Cfhttpmessageref mymessage = Cfhttpmessagecreateempty (Kcfallocatordefault, TRUE); Cfhttpmessageappendbytes (Mymessage, &data, numbytes)) {    //handle parsing error}


In the example, data is the numbytes that is added and the length of the database. Call cfhttpmessageisheadercomplete to verify that the header of the attached message is complete.

if (Cfhttpmessageisheadercomplete (mymessage)) {    //Perform processing.}


After the message is deserialized, you can call the following function to extract the information from the message:

    • cfhttpmessagecopybody used to get the message body
    • cfhttpmessagecopyheaderfieldvalue used to get a specific header field value
    • cfhttpmessagecopyallheaderfields used to get all message header fields
    • Cfhttpmessagecopyrequesturl used to get the message URL
    • Cfhttpmessagecopyrequestmethod used to get the message request method

When you no longer need the message, dispose of it and dispose of it appropriately.

Deserializing an incoming HTTP response

Just as creating an HTTP request is similar to creating an http response, deserializing an incoming http request with deserialization of the incoming http The response is similar. The only important difference is that when you call cfhttpmessagecreateempty, you must give the isrequest parameter a FALSE pass to specify that the message that will be created is a response message.

Serializing and sending HTTP requests using the Read stream

You can use the Cfreadstream object to serialize and send cfhttp requests. When you use the cfreadstream object to send a cfhttp request, open the stream because the message must be serialized in the same step to send. Using the Cfreadstream object to send a cfhttp request makes it easier to get the response from the request because the response is available as a property of the stream.

Serialize and send an HTTP request

Using the Cfreadstream object to serialize and send an HTTP request, first create a cfhttp request and set the message body and header in the Create cfhttp Request ( Creating a cfhttp Request) is described in. Then, call the cfreadstreamcreateforhttprequest function to create a Cfreadstream object that passes the request you just created. Finally, the read stream is opened through Cfreadstreamopen .

When Cfreadstreamcreateforhttprequest is called, a copy of the incoming Cfhttp request object is copied. Therefore, if necessary, you can release the Cfhttp request object immediately after calling cfreadstreamcreateforhttprequest .

Because when the cfhttp request is created, the read stream opens a socket connection to the server specified by the myurl parameter, which allows some time difference between the two. Opening the read stream also causes the request to be serialized and sent.

Listing 3-4 is an example of how to serialize and send HTTP requests

Manifest 3-4 Read stream serialization HTTP Request

Cfstringref url = cfstr ("http://www.apple.com"); Cfurlref Myurl = cfurlcreatewithstring (kcfallocatordefault, URL, NULL); Cfstringref Requestmethod = cfstr ("GET"); Cfhttpmessageref myrequest = Cfhttpmessagecreaterequest (Kcfallocatordefault,        Requestmethod, MYURL, Kcfhttpversion1_1); Cfhttpmessagesetbody (Myrequest, bodydata); Cfhttpmessagesetheaderfieldvalue (Myrequest, Headerfield, value); Cfreadstreamref Myreadstream = Cfreadstreamcreateforhttprequest (Kcfallocatordefault, myRequest); Cfreadstreamopen (Myreadstream);


Check for responses

After you have arranged the request to run the loop, you will eventually get a header to complete the callback. At this point, you can call Cfreadstreamcopyproperty to get a message response from the read stream.

Cfhttpmessageref myresponse = (cfhttpmessageref) cfreadstreamcopyproperty (Myreadstream, Kcfstreampropertyhttpresponseheader);


You can get the full status line from the message response by calling the cfhttpmessagecopyresponsestatusline function:

Cfstringref mystatusline = Cfhttpmessagecopyresponsestatusline (myresponse);


Get the status code for the message response by calling the cfhttpmessagegetresponsestatuscode function:

UInt32 Myerrcode = Cfhttpmessagegetresponsestatuscode (myresponse);


Note: If you are using this class synchronously (not scheduled to run loop), you must call Cfreadstreamread before calling Cfreadstreamcopyproperty and read the message first. The cfreadstreamread call is blocked until the data is available (or the connection fails). Do not use in your main application thread.

Handling Authentication Errors

If the status code returned by the cfhttpmessagegetresponsestatuscode function is 401(the remote server requires authentication information) or 407 (the proxy server requires authentication), and you need to attach the authentication information to the request and resend it. For information about how to handle authentication, review the HTTP server communication ( communicating with authenticating HTTP Servers) that requires authentication.

Handling REDIRECT Errors

When cfreadstreamcreateforhttprequest creates a read stream, the default dirty automatic redirection is disabled. If a request to send a Uniform Resource Locator or URL is redirected to another URL, sending the request will result in an error that states the code to 307 between. If you receive a redirect error, you need to close the stream, create a stream, enable redirection, and open the stream. See listing 3-5.

Manifest 3-5 redirect HTTP Stream

Cfreadstreamclose (Myreadstream); Cfreadstreamref Myreadstream =    cfreadstreamcreateforhttprequest (kcfallocatordefault, myRequest); Cfreadstreamsetproperty (Myreadstream, kcfstreampropertyhttpshouldautoredirect, kcfbooleantrue) = = False) {    // Something went wrong, exit}cfreadstreamopen (Myreadstream);


When you create a read stream, you may want to enable automatic redirection.

Cancel a pending request

Once the request has been sent, the remote server cannot be prevented from processing it. However, you no longer care about the response data, you can close the stream.

Important: Do not close the stream if another thread is waiting for the contents of a thread's stream. If you need to terminate the request, you should use non-blocking I/O, which is described in preventing blocking when using the stream (preventing Blocking when working with Streams). Be sure to remove the stream from your running loop before closing the stream.

Official Original address:

https://developer.apple.com/library/ios/documentation/Networking/Conceptual/CFNetwork/CFHTTPTasks/ Cfhttptasks.html#//apple_ref/doc/uid/tp30001132-ch5-sw2


Communicating with HTTP server (communicating with HTTP Servers)

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.