杏仁丶的iOS学习专题PHP经验分享iOS 知识点

关于HTTP请求头

2016-10-31  本文已影响3537人  神采飞扬_2015

客户端使用服务端API接口时,需构造HTTP请求头,一般情况下是初始化一个NSMutableURLRequest,然后设置请求方法、请求体,请求头,如下:

    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"];

猿题库的网络请求(YTKNetwork)已把请求方法、请求体,请求头等封装好允许用户重载进行自定义。包括:

#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;

请求头通过重写方法- (NSDictionary *)requestHeaderFieldValueDictionary;返回一个字典,然后在方法
- (AFHTTPRequestSerializer *)requestSerializerForRequest:(YTKBaseRequest *)request;中将网络请求序列化,供构造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};
}

下面具体说说请求头里几个字段的含义:

Accept-Encoding

Content-Type

Content-Length

Authorization

POST与GET区别

HTTP状态码大全

1、1** 信息,服务器收到请求,需要请求者继续执行操作
2、2** 成功,操作被成功接收并处理
3、3** 重定向,需要进一步的操作以完成请求
4、4** 客户端错误,请求包含语法错误或无法完成请求
5、5** 服务器错误,服务器在处理请求的过程中发生了错误

上一篇 下一篇

猜你喜欢

热点阅读