經過多一點研究後,我發現了一個注入我想要的編碼的地方。這是它沒有工作方式:
編碼不工作
初始化的requestOperationManager
:
self.requestOperationManager = [[AFHTTPRequestOperationManager alloc] init];
self.requestOperationManager.requestSerializer = [AFJSONRequestSerializer serializer];
使用requestOperationManager
來初始化操作
NSURLRequest *request = [NSURLRequest alloc] initWithURL:url]; // The problem is here
AFHTTPRequestOperation *operation = [self.requestOperationManager HTTPRequestOperationWithRequest:urlRequest success:^(AFHTTPRequestOperation *operation, id responseObject) {
// Success
} failure:^(AFHTTPRequestOperation *operation, NSError *error) {
// Failure
}];
[self.requestOperationManager.operationQueue addOperation:operation];
[operation start];
方式有更多的控制
AFHTTPRequestSerializer
也可以創建請求,您可以使用自己的序列化。
初始化的requestOperationManager
並添加查詢字符串序列化區塊:
self.requestOperationManager = [[AFHTTPRequestOperationManager alloc] init];
self.requestOperationManager.requestSerializer = [AFJSONRequestSerializer serializer];
[self.requestOperationManager.requestSerializer setQueryStringSerializationWithBlock:^NSString * _Nonnull(NSURLRequest * _Nonnull request, id _Nonnull parameters, NSError * _Nullable __autoreleasing * _Nullable error) {
if ([parameters isKindOfClass:[NSString class]]) {
NSString *yourEncodedParameterString = // What every you want to do with it.
return yourEncodedParameterString;
}
return parameters;
}];
現在改變你如何創建NSURLRequest
:
NSString *method = @"GET";
NSString *urlStringWithoutQuery = @"http://example.com/";
NSString *query = @"datetime=2016-07-06T12:15:42+0200"
NSMutableURLRequest *urlRequest = [self.requestOperationManager.requestSerializer requestWithMethod:method URLString:urlStringWithoutQuery parameters:query error:nil];
這是重要,你拆你的網址。使用url而不用查詢URLString
參數,只查詢parameters
參數。通過使用requestWithMethod:URLString:parameters:error
它將調用上面提供的查詢字符串序列化塊,並根據需要對參數進行編碼。
AFHTTPRequestOperation *operation = [self.requestOperationManager HTTPRequestOperationWithRequest:urlRequest success:^(AFHTTPRequestOperation *operation, id responseObject) {
// Success
} failure:^(AFHTTPRequestOperation *operation, NSError *error) {
// Failure
}];
[self.requestOperationManager.operationQueue addOperation:operation];
[operation start];