这是标题:
"url": "{{host}}/images/bla",
"method": "OST",
"header": [
{
"key": "Content-Type",
"value": "application/json",
"description": ""
},
{
"key": "Authorization",
"value": "Bearer token",
"description": ""
}
],
"body": { ... }
我尝试分两种情况解决:
案例 1(崩溃):
NSDictionary *headerDict = @{@"key": @"Content-Type",
@"value": @"application/json",
@"description": @""};
NSDictionary *headerDict1 = @{@"key": @"Authorization",
@"value": kBearerKey,
@"description": @""};
NSArray *headerArray = @[headerDict, headerDict1];
[weakSelf.requestOperationManager.requestSerializer setValue:headerArray forHTTPHeaderField"header"];
案例 2(不会崩溃但也不起作用):
weakSelf.requestOperationManager.requestSerializer = [AFHTTPRequestSerializer serializer];
[weakSelf.requestOperationManager.requestSerializer setValue"Content-Type" forHTTPHeaderField"key"];
[weakSelf.requestOperationManager.requestSerializer setValue"application/json" forHTTPHeaderField"value"];
[weakSelf.requestOperationManager.requestSerializer setValue"Authorization" forHTTPHeaderField"key"];
[weakSelf.requestOperationManager.requestSerializer setValue:kBearerKey forHTTPHeaderField"value"];
无论如何,在 Case 1 中会生成一个警告(并且也会导致崩溃),因为 setValue
应该是 NSString
而不是 NSArray
.
例如,您可以将 NSMutableDictionary 中的所有 header 值保留为键/值对
NSDictionary *headersDict = @{@"Content-Type": @"application/json",
@"Authorization": kBearerKey };
然后你可以迭代键值并设置http头
[headersDict enumerateKeysAndObjectsUsingBlock:^(NSString *key, NSString *obj, BOOL *stop) {
[requestManager.requestSerializer setValuebj forHTTPHeaderField:key];
}];
在您的情况下,您使用的是数组。您可以迭代数组并设置 header 值,希望这会有所帮助。
for (NSDictionary *dict in headerArray) {
NSString *key = [dict objectForKey"key"];
NSString *value = [dict objectForKey"value"];
[requestManager.requestSerializer setValue:value forHTTPHeaderField:key];
}
关于ios - 如何使用数组作为 header 和 AFNetworking 进行 POST,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44650789/
欢迎光临 OStack程序员社区-中国程序员成长平台 (https://ostack.cn/) | Powered by Discuz! X3.4 |