Client usesServerAPI Interface , you need to construct the HTTP request header. Generally, you initialize an NSMutableURLRequest, and then set the request method , request body, and 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"];
YuanTiku's network request (YTKNetwork) has encapsulated the request method, request body, and request header to allow users to overload, 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 WILL be called on the main thread, just like `requestCompleteFilter`. - (void)requestCompletePreprocessor; /// Called on the main thread after request succeeded. - (void)requestCompleteFilter; /// Called on background thread after request succeded but before switching to main thread. See also /// `requestCompletePreprocessor`. - (void)requestFailedPreprocessor; /// Called on the main thread when request failed. - (void)requestFailedFilter; /// The baseURL of request. This should only contain the host part of URL, e.g., http://www.example.com. /// See also `requestUrl` - (NSString *)baseUrl; /// The URL path of request. This should only contain the path part of URL, e.g., /v1/user. See alse `baseUrl`. /// /// @discussion This will be concated with `baseUrl` using [NSURL URLWithString:relativeToURL]. /// Because of this, it is recommended that the usage should stick to rules stated above. /// Otherwise the result URL may not be correctly formed. See also `URLString:relativeToURL` /// for more information. /// /// Additionaly, if `requestUrl` itself is a valid URL, it will be used as the result URL and /// `baseUrl` will be ignored. - (NSString *)requestUrl; /// Optional CDN URL for request. - (NSString *)cdnUrl; /// Requset timeout interval. Default is 60s. /// /// @discussion When using `resumableDownloadPath`(NSURLSessionDownloadTask), the session seems to completely ignore /// `timeoutInterval` property of `NSURLRequest`. One effective way to set timeout would be using /// `timeoutIntervalForResource` of `NSURLSessionConfiguration`. - (NSTimeInterval)requestTimeoutInterval; /// Additional request argument. - (nullable id)requestArgument; /// Override this method to filter 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 authorization. Should be formed as @[@"Username", @"Password"]. - (nullable NSArray<NSString *> *)requestAuthorizationHeaderFieldArray; /// Additional HTTP request header field. - (nullable NSDictionary<NSString *, NSString *> *)requestHeaderFieldValueDictionary; /// Use this to build custom request. If this method return non-nil value, `requestUrl`, `requestTimeoutInterval`, /// `requestArgument`, `allowsCellularAccess`, `requestMethod` and `requestSerializerType` will all be 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 will be used to test if `responseJSONObject` is correctly formed. - (nullable id)jsonValidator; /// This validator will be used to test if `responseStatusCode` is valid. - (BOOL)statusCodeValidator;
. The request header is returned by overriding the method - (NSDictionary *)requestHeaderFieldValueDictionary;
and then in the method - (AFHTTPRequestSerializer *)requestSerializerForRequest:(YTKBaseRequest *)request;
Network request serialization, used to construct 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}; }
Let’s talk about the meaning of several fields in the request header:
Indicates that the local can receive data in compressed format, and the server will compress the large file and send it back to the client. After the client completes the reception, it will decompress the data locally.
1. The client sends an HTTP request to the Web server. The request contains Accept-Encoding: gzip, deflate. (Tell the server that the browser supports gzip compression).
2. After receiving the request, the server generates the original Response, which contains the original Content-Type and Content-Length.
Others
application/x-www-form-urlencoded: The data is encoded as name/value pairs, which is the standard encoding format; multipart/form-data: The form data is encoded as a message, Each control on the page corresponds to a section in the message. text/plain: Form data is encoded as plain text without any controls or formatting characters.
1. When action is get, the browser uses the x-www-form-urlencoded encoding method to convert the form data into a string (name1=value1&name2=value2...), and then converts this word Append the string to the end of the url, split it with ?, and load this 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 there is no type=file control, just use the default application/x-www-form-urlencoded. But if there is type=file, multipart/form-data will be used. The browser will divide the entire form into control units, and add Content-Disposition(form-data or file), Content-Type (default is text/plain), name( Control name) and other information, and add a separator (boundary).
represents the transmission length of the HTTP message entity. Message entity length: Entity-length, the length of the message-body before compression;
Transmission length of the message entity: Content-length, the length of the message-body after compression. (Dictionary of parameters spliced together)
Authorization mechanismDetermined according to the rules set by the server.
1. GET is harmless when the browser rolls back. And POST will submit the request again.
2. The URL address generated by GET can be Bookmarked, but POST cannot.
3. GET requests will be actively cached by the browser, but POST will not unless manually set.
4. GET requests can only be URL encoded, while POST supports multiple encoding methods.
5. GET
Request parameters will be completely retained in the browser history, while the parameters in POST will not be retained. 6. The parameters transmitted in the URL of the GET request have length limits, but there are no length limits for POST.
7. Regarding the parameter’s
data type, GET only accepts ASCII characters, while POST has no restrictions. 8. GET is less
safe than POST because the parameters are directly exposed on the URL, so it cannot be used to pass sensitive information. 9. GET parameters are passed through the URL, and POST is placed in the Request body.
1. HTTP is a protocol based on
TCP/IP on how data communicates in the World Wide Web. The bottom layer of HTTP is TCP/IP. So the bottom layer of GET and POST is also TCP/IP, that is to say, GET/POST are both TCP links. GET and POST can do the same thing. You need to add request body to GET and url parameters to POST. Technically, it is completely feasible. HTTP is just a code of conduct, while TCP is the basis for how GET and POST are implemented. 2. There is no requirement for HTTP. If the Method is POST data, it must be placed in the BODY. There is no requirement. If the Method is GET, the data (parameters) must be placed in the URL and not in the BODY. That is, GET and POST have nothing to do with how the data is delivered. The HTTP protocol has no length limit for both GET and POST. Security and insecurity have nothing to do with GET and POST. 3. GET generates one TCP data packet; POST generates two TCP data packets. For GET requests, the browser will send the http header and data together, and the server will respond with 200 (returning data); for POST, the browser will send the header first, and the server will respond with 100 continue
, and the browser will Send data again, and the server responds with 200 ok (returning data).
1, 1** Information, the server receives the request and needs the requester to continue performing the operation
2, 2* * Success, the operation was successfully received and processed
3, 3** Redirect, further operations are required to complete the request
4, 4** Client error, the request contains a syntax error or Unable to complete the request
5, 5** Server error, an error occurred while the server was processing the request
The above is the detailed content of HTTP request header. For more information, please follow other related articles on the PHP Chinese website!