AFNetworking2.0 source parsing < two >

Source: Internet
Author: User
Tags http post

In this article we continue to look at Afnetworking's next module-afurlrequestserialization. Afurlrequestserialization is used to help build nsurlrequest, mainly doing two things: 1. Build a normal Request: Format the request parameters to generate an HTTP Header. 2. Build the multipart request. Take a look at what it did and how it was done at these two points. 1. Building a general request A. Formatting request parametersIn general, we request will be in accordance with the key=value of various parameters, get method parameters directly added to the URL, the post method on the body, Nsurlrequest does not encapsulate the resolution of this parameter, we can only spell a good string. Afnetworking provides an interface that allows parameters to be nsdictionary, Nsarray, nsset These types, and then internally parsed into strings to be assigned to Nsurlrequest. The conversion process is roughly the same:
  1. @{
  2. @ "name": @"bang",
  3. @ "phone": @{@"mobile": @ "xx", @"Home": @"xx"},
  4. @"families": @[@"father", @"mother"],
  5. @"nums": [Nsset setwithobjects:@"1" @"2", nil]
  6. }
  7. -
  8. @[
  9. Field: @"name", Value: @"bang",
  10. Field: @"Phone[mobile]", Value: @"xx",
  11. Field: @"phone[home]", Value: @"xx",
  12. Field: @"families[]", Value: @"Father",
  13. Field: @"families[]", Value: @"mother",
  14. Field: @"Nums", Value: @"1",
  15. Field: @"Nums", Value: @"2",
  16. ]
  17. -
  18. name=bang&phone[mobile]=xx&phone[home]=xx&families[]=father&families[]=mother&nums=1& num=2
The first part is the data that the user passes in, and supports three data structures including Nsarray,nsdictionary,nsset. The second part is converted into Afnetworking's own data structure, each key-value pair is represented by an object Afquerystringpair, and the function is to generate their own key=value strings based on different string encodings. The main function is afquerystringpairsfromkeyandvalue, see source comments. The third part is the final generation of nsurlrequest available string data, and the parameters are URL-encoded in the afquerystringfromparameterswithencoding function. Finally, when the data is assigned to nsurlrequest according to different HTTP methods, for the Get/head/delete method, add the parameters to the URL, for other such as Post/put method, add data to the body, and set the HTTP header, Tells the encoding of the service-side string. b.http HeaderAfnetworking helped you assemble some HTTP request headers, including the language accept-language, to read the local language according to the [Nslocale Preferredlanguages] method, and the language that the high-speed server can accept. There is also a build user-agent, and a basic Auth authentication interface to help you put the user name password base64 encoded into the HTTP request header. See source notes. C. Other formatting methodsHTTP request parameters are not necessarily key=value form, can be any form of data, can be in JSON format, Apple plist format, binary protobuf format, etc., Afnetworking provides a way to easily extend support for these formats, The JSON and plist formats are implemented by default. See the source code class Afjsonrequestserializer and Afpropertylistrequestserializer. 2. Build multipart RequestBuilding a multipart request is a huge feature, and the code in Afurlrequestserialization 2/3 is doing it. A.multipart Protocol IntroductionMultipart is the HTTP protocol for the Web form a new upload file protocol, the Protocol document is rfc1867, which is based on the HTTP POST method, the data is also placed on the body, the difference from the normal post method is that the data is not key=value form, key= The value form difficult to represent the file entity, for this multipart protocol added delimiter, has its own format structure, roughly as follows:-aab03xcontent-disposition:form-data; Name= "Name" Bang--aab03xcontent-disposition:form-data; Name= "pic"; Filename= "Content.txt" Content-type:text/plain ... contents of bang.txt ...--aab03x--above represents data Name=bang and a file, Content.txt is a filename, ... contents of bang.txt ... is the file entity content. The delimiter-aab03x can be customized and written in the HTTP header: Content-type:multipart/form-data, boundary=aab03x each part has its own head, indicating the data type of this part and some other parameters, For example, the file name, the normal field key. The last delimiter adds two more horizontal, indicating that the data has ended:-aab03x-. B. ImplementationNext talk about how to construct the data in the multipart, the simplest way is to directly spell the data, to send a file, directly read all the contents of the file, and then in accordance with the above protocol plus the head and delimiter, splicing good data after throwing to nsurlrequest body can be sent, very simple. But this is not available, because the file can be very large, so the spelling of the whole file into memory, it is likely to burst the memory. The second method is not to read out the file, not in memory, but create a temporary file, in this file splicing data, and then throw the file address to Nsurlrequest BodyStream, so that when the upload is a shard read this file, will not burst memory, However, each upload requires a new temporary file, the management of this temporary file is also very troublesome. The third method is to build their own data structure, only to save the file address to upload, edge-upload side-by-side spelling data, upload is fragmented, spelling data is also fragmented, to the file entity part of the original file is read directly from the Shard. This method does not have the above two kinds of problems, just realize it is not the two simple, afnetworking is to achieve this third method, but also further, in addition to the file, you can also add a number of other different types of data, including NSData, and InputStream. The afnetworking multipart request is used in this way:
  1. Afhttprequestoperationmanager *manager = [Afhttprequestoperationmanager manager];
  2. Nsdictionary *parameters = @{@"foo": @"Bar"};
  3. Nsurl *filepath = [Nsurl fileurlwithpath:@"File://path/to/image.png"];
  4. [Manager post:@"Http://example.com/resources.json" Parameters:parameters constructingbodywithblock:^ (ID FormData) {
  5. [FormData appendpartwithfileurl:filepath name:@"image" Error:nil];
  6. } success:^ (afhttprequestoperation *operation, id responseobject) {
  7. NSLog (@"Success:%@", responseobject);
  8. } failure:^ (Afhttprequestoperation *operation, Nserror *error) {
  9. NSLog (@"error:%@", error);
  10. }];
Here, a Afstreamingmultipartformdata object is provided to the user by Constructingbodywithblock, and several append methods of the object can be added to add different types of data, including fileurl/ The Nsdata/nsinputstream,afstreamingmultipartformdata internally transfers these append data to different types of afhttpbodypart, adding to the custom In the Afmultipartbodystream. Finally, the Afmultipartbodystream was assigned to the original Nsmutableurlrequest BodyStream. This bodystream is read by nsurlconnection when the request is sent, and this bodystream-read:maxlength is called when the data is read: method, Afmultipartbodystream overrides this method, Continuously read the Afhttpbodypart data that append came in until it is finished reading. Afhttpbodypart encapsulates the assembly and reading of parts of the data, and a Afhttpbodypart is a block of data. In fact, three types (fileurl/nsdata/nsinputstream) of data in Afhttpbodypart are turned into Nsinputstream, reading the data just read this inputstream. InputStream only the entity that holds the data, does not include the delimiter and the head, the Afhttpbodypart is the edge reads the splicing data, uses a state machine to determine now the data reads to which part, as well as saves this state has been read the number of bytes, in order to locate the data location to read, see Afhttpbodypart's-read:maxlength: method. The Afmultipartbodystream encapsulates the reading of the entire multipart data, mainly based on the location of the read to determine which afhttpbodypart to read now. Afstreamingmultipartformdata provides a friendly append interface, and assigns the constructed Afmultipartbodystream back to Nsmutableurlrequest, which is roughly as follows: C.nsinputstream sub-classNsurlrequest's Sethttpbodystream accepts a nsinputstream* parameter, so if we want to customize InputStream, is it okay to create a subclass of Nsinputstream? In fact, do not, after doing so with Nsurlrequest to send a request will lead to crash, prompt [xx _scheduleincfrunloop:formode:]: Unrecognized selector. This is because Nsurlrequest actually accepts not nsinputstream objects, but corefoundation cfreadstreamref objects, because Cfreadstreamref and Nsinputstream are tol L-free bridged, can be freely converted, but Cfreadstreamref will use Cfstreamschedulewithrunloop this method, when it calls to this method, object-c of toll-free bridging The mechanism invokes the corresponding function of the Object-c object Nsinputstream, which is called to _scheduleincfrunloop:formode: If this method is not implemented, it will be crash. See this article for more details. 3. SOURCE Notes
    1. Afurlrequestserialization.m

AFNetworking2.0 source parsing < two >

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.