http://www.php.cn/code/10550.html "target=" _blank "> client uses the Server API interface, the need to construct an HTTP request header, in general, the initialization of a nsmutableurlrequest, Then set the request method, the request body, the request header, as follows:
Nsmutableurlrequest *request = [nsmutableurlrequest requestwithurl:[nsurl Urlwithstring:url] CachePolicy: Nsurlrequestuseprotocolcachepolicy timeoutinterval:30.0]; [Request sethttpmethod:@ "POST"]; [Request Sethttpbody:bodydata]; [Request setvalue:@ "gzip, deflate" forhttpheaderfield:@ "accept-encoding"]; [Request setvalue:@ "application/x-www-form-urlencoded; charset=utf-8" forhttpheaderfield:@ "Content-Type"]; [Request setvalue:[nsstring stringwithformat:@ "%lu", (unsigned long) bodydata.length] forhttpheaderfield:@ " Content-length "]; [Request Setvalue:authorization forhttpheaderfield:@ "Authorization"];
The network request of the ape Question Bank (Ytknetwork) has put the request method, the request body, the request first class encapsulation to allow the user overloads to customize. Including:
#pragma mark-subclass override///=============================================================================// /@name Subclass override///=============================================================================/// Called on background thread after request succeded but before switching to main thread. Note if///Cache is loaded, this method would be called on the main thread, and just like ' Requestcompletefilter '.-(void) requ estcompletepreprocessor;///called on the main thread after request succeeded.-(void) requestcompletefilter;///called O n Background thread after request succeded but before switching to main thread. See also///' Requestcompletepreprocessor '.-(void) requestfailedpreprocessor;///called on the main thread when request F ailed.-(void) requestfailedfilter;///the BaseURL of request. This should only contain the host part of the URL, e.g., http://www.example.com.///see also ' Requesturl '-(NSString *) baseur l;///the URL path of the request. This should only containThe path part of the URL, e.g.,/v1/user. See Alse ' BaseUrl './/////-@discussion This would be a concated with ' baseUrl ' using [Nsurl urlwithstring:relativetourl]./// Because of this, it's recommended, the usage should stick to rules stated above.///OTHERWI Se The result URL is correctly formed. See also ' urlstring:relativetourl '///For more information.//////additionaly, if ' Requesturl ' I Tself is a valid URL, it'll be used as the result URL and///' baseUrl ' would be ignored.-(NSString *) reques turl;///Optional CDN URL for request.-(NSString *) cdnurl;///requset timeout interval. Default is 60s.//////@discussion when using ' Resumabledownloadpath ' (Nsurlsessiondownloadtask), the session seems to comp letely ignore///' timeoutinterval ' property of ' nsurlrequest '. One effective-to-set timeout would be using///' timeoutintervalforresource ' of ' nsurlsessionconfiguration '.-(Nstimeinterval) requesttimeoutinterval;///Additional request argument.-(nullable ID) requestargument;///Override this method to fi Lter requests with certain arguments when caching.-(ID) cachefilenamefilterforrequestargument: (ID) argument;///HTTP Request method.-(Ytkrequestmethod) requestmethod;///request Serializer type.-(Ytkrequestserializertype) requestserializertype;///Response Serializer type. See also ' Responseobject '.-(Ytkresponseserializertype) responseserializertype;///Username and password used for HTTP au Thorization. Should be formed as @[@ "Username", @ "Password"].-(Nullable nsarray<nsstring *> *) requestauthorizationheaderfieldarray;///Additional HTTP Request Header field.-(Nullable nsdictionary<nsstring *, NSString *> *) requestheaderfieldvaluedictionary;///use the To build custom request. If This method return Non-nil value, ' Requesturl ', ' requesttimeoutinterval ',///' requestargument ', ' Allowscellularaccess ', ' requestmethod ' and ' Requestserializertype ' wilL all being ignored.-(nullable nsurlrequest *) buildcustomurlrequest;///should use CDN when sending request.-(BOOL) Usecdn; Whether the request is allowed to use the cellular radio (if present). Default is yes.-(BOOL) allowscellularaccess;///The validator would be a used to test if ' responsejsonobject ' is correctly f ormed.-(Nullable ID) jsonvalidator;///This validator'll be used to test if ' Responsestatuscode ' is valid.-(BOOL) statu Scodevalidator;
The request header - (NSDictionary *)requestHeaderFieldValueDictionary;
returns a dictionary by overriding the method, and then the method
- (AFHTTPRequestSerializer *)requestSerializerForRequest:(YTKBaseRequest *)request;
Serializes the network request for use by the construction nsurlsessiontask.
-(Nsdictionary *) requestheaderfieldvaluedictionary { NSString *paraurlstring = Afquerystringfromparameters ([ Self requestargument]); NSString *authorization =[[ytknetworkconfig Sharedconfig] getauthorization:[self RequestUrl]]; return @{@ "accept-encoding": @ "gzip, deflate", @ "Content-type": @ "application/x-www-form-urlencoded; charset= Utf-8 " @" content-length ": [NSString stringwithformat:@"%lu ", (unsigned long) paraurlstring.length], @" Authorization ": Authorization};}
The following specifically explains the meaning of several fields in the request head:
Accept-encoding
Indicates that data in a compressed format can be received locally, and the server will compress large files and then send them back to the client when processing. The client receives the data and extracts it locally after it is completed.
Gzip: File compression for Unⅸ systems, Gzip encoding on HTTP protocol is a technique used to improve the performance of Web applications. High-traffic Web sites often use gzip to make users feel faster. This generally refers to the WWW server installed in a feature, when someone to access the site in this server, the server of this feature will compress the content of the Web page is transmitted to the visiting Computer browser display. Generally, plain text content can be compressed to 40% of the original size, which makes the data transfer speed faster. Of course, this will also increase the server load, the general server is equipped with this function module.
Deflate: A lossless compression technology that uses the LZ77 algorithm with Huffman coding (Huffman Coding) without proprietary algorithms.
The difference between HTTP content encoding and HTTP compression: in the HTTP protocol, the content (that is, the body part) can be encoded and can be encoded using gzip. So as to achieve the purpose of compression. You can also use other encodings to scramble or encrypt content to prevent unauthorized third parties from seeing the contents of the document. So we say that HTTP compression, in fact, is a kind of HTTP content encoding.
The process of HTTP compression:
1, the client sends HTTP request to the Web server, the request has accept-encoding:gzip, deflate. (Tell the server that the browser supports gzip compression).
2. After the server receives the request, it generates the original response, which has the original Content-type and Content-length.
3, the server through gzip, to encode response, after the header has Content-type and content-length (compressed size), and added Content-encoding:gzip. The response is then sent to the client.
4, the client received response, according to Content-encoding:gzip to decode the response. Gets to the original response, and then processes the display of the data.
Other: Compress indicates that the entity uses the UNIX file compression program; The identity indicates that the entity is not encoded. When there is no content-encoding header, it is assumed that this is the case. gzip, compress, and deflate codes are lossless compression algorithms that reduce the size of transmitted messages without causing loss of information. Gzip is usually the most efficient and most widely used.
Content-type
Represents a content type, typically a client-side content-type that defines the type of network file and the encoding of the Web page, and determines in what form and in what encoding the client will read the file. That is, the type that identifies the data that is sent or received, and the client determines how the data is opened based on that parameter.
Application/x-www-form-urlencoded: Data is encoded as a name/value pair, which is the standard encoding format; Multipart/form-data: The form data is encoded as a message, and each control on the page corresponds to a part of the message. Text/plain: Form data is encoded in plain text with no control or formatting characters.
1, when the action is get, the browser uses x-www-form-urlencoded encoding to convert the form data into a string (Name1=value1&name2=value2 ... ), and then append the string to the URL, using the. Split, to load the new URL.
2. When the action is post, the browser encapsulates the form data into the HTTP body and then sends it to the server. If you don't have a type=file control, you can use the default application/x-www-form-urlencoded. But if you have type=file, you will need to use Multipart/form-data. The browser splits the entire form into units of controls and adds Content-disposition (form-data or file) to each section, Content-type (default = Text/plain), name (control name), and so on. and add the separator (boundary).
Content-length
Represents the transmission length of an HTTP message entity. Message entity Length: entity-length, the length of the message-body before compression;
The transmission length of the message entity: Content-length, the length of the compressed message-body. (Dictionary of parameter stitching)
Authorization
HTTP Basic authentication is a way to allow a Web browser, or other client program, to provide credentials in the form of a user name and password when requested. The authorization mechanism is determined according to the rules set by the service end.
The difference between authentication (authentication) and Authorization (authorization): You need to be on board, you have to show your ID and ticket, ID is to prove that you Zhang San is really you Zhang three, this is authentication And the ticket is to prove that you Zhang San did buy a ticket to get on the plane, this is authorization. You want to login to the forum, enter the user name Zhang San, password 1234, the password is correct, prove that you Zhang San is really Zhang San, this is authentication; another check user Zhang Three is a moderator, so have the right to add fine delete others, this is authorization.
Post vs. get differences
Stand in HTML angle:
1, get is harmless when the browser is rolled back, and post will submit the request again.
2, get generated URL address can be bookmark, and post is not.
3, get requests will be the browser active cache, and post will not, unless manually set.
4, get requests can only be URL-encoded, and post supports a variety of encoding methods.
5. The GET request parameters are kept intact in the browser history, and the parameters in post are not retained.
6, the GET request in the URL to transmit the parameters are limited in length, and post is there.
7. For data types of parameters, get accepts only ASCII characters, while Post has no restrictions.
8, get is more unsafe than post, because parameters are directly exposed to the URL, so it cannot be used to pass sensitive information.
9. The get parameter is passed through the URL and the post is placed in the request body.
Stand in the HTTP angle:
1. HTTP is a TCP/IP-based protocol about how data is communicated in the World Wide Web. The underlying HTTP is TCP/IP. So the bottom of GET and post is TCP/IP, which means that get/post are TCP links. Get and post can do the same thing. You have to add the request body to the GET, and the URL parameter to the post, technically it's all in line. HTTP is just a code of conduct, and TCP is the basic of how get and post are implemented.
2, HTTP is not required, if the method is the post data will be placed in the body. There is no requirement that if the method is get, the data (parameters) must be placed in the URL instead of being placed in the body. That is, get and post have no relation to how the data is passed. The HTTP protocol has no limit on the length of both get and post. Security insecurity is not related to get, post.
3. Get generates a TCP packet, and post generates two TCP packets. For the Get mode request, the browser will send the HTTP header and data, the server response 200 (return data), and for post, the browser first sends the header, the server responds to the continue, the browser sends data, the server response 200 OK (return data).
HTTP status Code Daquan
1, 1** information, the server receives the request, requires the requestor to continue the Operation
2, 2** succeeded, the operation was successfully received and processed
3, 3** Redirect, requires further action to complete the request
4, 4** client error, the request contains a syntax error or cannot complete the request
5, 5** Server error, the server has an error while processing the request