HTTP request header

PHPz
Release: 2023-03-07 10:14:02
Original
2751 people have browsed it

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"];
Copy after login

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;
Copy after login

. 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};
}
Copy after login

Let’s talk about the meaning of several fields in the request header:

Accept-Encoding

represents the content type, which generally refers to the Content-Type that exists on the client and is used to define the type and type of network files. The encoding of the web page determines the form and encoding in which the client will read the file. That is, it is used to identify the type of data sent or received. The client determines how to open the data based on this parameter.

  • 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).

  • Content-Length

    • 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

    • ##HTTP basic authentication is a method used to allow web browsers, or other client programs Login by providing credentials in the form of username and password when requested.

      Authorization mechanismDetermined according to the rules set by the server.

    • The difference between authentication and authorization: If you want to board the plane, you need to show your ID card and ticket. The ID card is to prove that Zhang San is really you. Zhang San, this is authentication; and the ticket is to prove that you Zhang San actually bought the ticket and can board the plane, this is authorization. You need to log in to the forum, enter the user name Zhang San, password 1234, and the password is correct, which proves that you Zhang San is indeed Zhang San, this is authentication; then check that user Zhang San is a moderator, so he has the authority to add and delete other people's posts. This It’s authorization.

    The difference between POST and GET

    HTTP status codeCollection

    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!

    Related labels:
    source:php.cn
    Statement of this Website
    The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
    Popular Tutorials
    More>
    Latest Downloads
    More>
    Web Effects
    Website Source Code
    Website Materials
    Front End Template
    About us Disclaimer Sitemap
    php.cn:Public welfare online PHP training,Help PHP learners grow quickly!